On 2/16/06, bsnipes <[EMAIL PROTECTED]> wrote:
> I am just learning Python and Django and can't seem to be able to
> figure this out. As a test app I am trying to make a 'foodlog' app to
> track food eaten, when, and calories. My model file looks like this:
>
> ----------- snip
> from django.core import meta
> class Period(meta.Model):
> name = meta.CharField(maxlength=40)
>
> def __repr__(self):
> return self.name
>
> class META:
> admin = meta.Admin()
>
> class Food(meta.Model):
> eat_date = meta.DateTimeField('date eaten')
> description = meta.CharField(maxlength=60)
> period = meta.ForeignKey(Period)
> calories = meta.IntegerField()
>
> def __repr__(self):
> return str(self.id)
>
> class META:
> admin = meta.Admin(
> list_display =
> ('eat_date','description','period','calories'),
> list_filter = ['eat_date'],
> search_fields = ['description'],
> )
> --------- end snip
>
> In the periods table the entries in the db for name are 'Breakfast',
> 'Lunch', 'Dinner' and 'Snack'.
>
> I am creating a list of entries in the foods table and a details view
> when an item is clicked on. On the 'details' view it pulls info from
> the foods table and a periods_id but not the 'name' field
> automatically. Do I need to do a custom sql join statement to pull in
> the name field when retrieving an entry from foods or is there a
> 'django' way that I don't understand?
Hey Brian,
There's no need to do custom SQL in your case. When you have a Food
object "f", just do "f.get_period()" to return its related Period
object.
When you retrieve the Food object in the first place --
foods.get_object(pk=whatever) -- pass the select_related=True
argument. That'll automatically grab and cache the related Period
object as well. For example:
foods.get_object(pk=3, select_related=True)
If you don't do select_related=True, your call to f.get_period() will
execute a second SQL statement.
Adrian
--
Adrian Holovaty
holovaty.com | djangoproject.com | chicagocrime.org
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---