Custom models fields?
Check out the new site at https://rkblog.dev.
14 July 2008
Comments
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)
RkBlog
Check out the new site at https://rkblog.dev.
Comment article