RkBlog

Hardware, programming and astronomy tutorials and reviews.

Custom models fields?

I was wondering how to make a ForeignKey on a model and limit the choices in some way (for example allow adding subcategories only to root categories). So why not make a new class, that inherits models.ForeignKey and overwrite method that return the choices? My test code that works (it probably can be done a bit better...):

class FK(models.ForeignKey):
	def __init__(self, to, to_field=None, **kwargs):
		models.ForeignKey.__init__(self, to, to_field=None, **kwargs)
	def get_choices(self, include_blank=True):
		c = Category.objects.filter(id__gt=2)
		returnList = []
		for cc in c:
			returnList.append([cc.id, cc.cat_name])
		return returnList
	

class Category(models.Model):
	cat_name = models.CharField(maxlength=255, verbose_name=_("Category Name"))
	cat_order = models.PositiveSmallIntegerField(default=0, verbose_name=_("Order"))
	cat_foo = FK('self', verbose_name=_("test"), blank=True, null=True)
We override get_choices, and we are done. Other custom fields (not relations) should be even easier to create. Just look at django/db/models/fields/.

RkBlog

Django web framework tutorials, 14 July 2008, Piotr Maliński

Comment article