On Mar 27, 2006, at 11:40 PM, Ivan Sagalaev wrote:
> > Todd O'Bryan wrote: > >> The tutorial explains how to get objects based on field values, but I >> need to get a subset of the objects in a OneToMany relationship based >> on one of their values. Here's an example: >> >> BRANCH_KINDS = ((0, 'Main'), (1, 'Auxiliary'), (2, 'Dead'),) >> >> class Trunk(meta.Model): >> name = meta.CharField(max_length=10) >> >> class Branch(meta.Model): >> trunk = meta.ForeignKey(Trunk) >> kind = meta.IntegerField(choices=BRANCH_KINDS) >> >> Say I have a Trunk object and want to get all of its Auxiliary >> branches. How the heck do I do that? >> >> > Since your DB doesn't know anything about BRANCH_KINDS values you > should > manually find a number corresponding a value and use it for lookup: > > from myproject.myapp.models import BRANCH_KINDS > > index = [bk[1] for bk in BRANCH_KINDS].index('Auxillary') > trunks.get_branch_list(kind__exact=BRANCH_KINDS[index][0]) > > But it anyway looks strange that you need to make a DB lookup based on > values intended only for display purposes and that can be changed > any time. Thanks. It was the second line I couldn't figure out. (Simple in hindsight.) Your comment at the end got me thinking, though. Writing trunk.get_branch(kind__exact=2) is not very illuminating, but you're correct that the value 'Dead' could get changed later. In Java, I'd use constants for the integer values public static final int DEAD = 2; but that seems to violate DRY, because the semantics is already listed in the choices list. I like using integers for what end up being enumerated types because they don't take much space in the database and, as you mentioned, it's easy to change the English version without having to do anything to the db representation. Is there a better way to do this kind of thing? Todd --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~----------~----~----~----~------~----~------~--~---