from:
http://www.djangoproject.com/documentation/db-api/
 Backward

If a model has a ForeignKey, instances of the foreign-key model will have
access to a Manager that returns all instances of the first model. By
default, this Manager is named FOO_set, where FOO is the source model name,
lowercased. This Manager returns QuerySets, which can be filtered and
manipulated as described in the "Retrieving objects" section above.
 The 'Django-y' way is to access the related fields through a related
manager.  In your case Books is related to Person via pid which should have
models.ForeignKey(Person), I assume it is in your model.  So you would just
get the books related to the person via:
p = Person.objects.get(pk=1)
p.books_set.all()

Also, generally in Django, you do not necessarily need to specify the id (a
field called id will be created for you) and people usually will give
related fields names that are more descriptive of the object accessed, i.e.
:

class Person(models.Model):
    fname = models.CharField(max_length=50)
    lname = models.CharField(max_length=50)

class Books(models.Model)
    name = models.CharField(max_length=50)
    person = models.ForiegnKey(Person)

as when you use it you are getting the related objects rather than just
related ids, but this is obviously a matter of ones personal taste.
hth,
-richard


On 6/9/08, Huuuze <[EMAIL PROTECTED]> wrote:
>
>
> I have the following models in my models.py file:
>
> >> class Person(models.Model):
> >>   pid = models.AutoField(primary_key=True)
> >>   fname = models.CharField(max_length=50)
> >>   lname = models.CharField(max_length=50)
>
> >> class Books(models.Model)
> >>   bid = models.AutoField(primary_key=True)
> >>   name = models.CharField(max_length=50)
> >>   pid = models.ForiegnKey()
>
> In my views.py, I'd like to run a query that returns a list of people
> and their books, where "st" are the "search terms" being passed into
> the view:
>
> >> results = Person.objects.filter(Q(fname__istartswith=st) |
> Q(lname__istartswith=st))
>
> This only returns the "Person" object.  Is there a "Django-y" way to
> have it return both associated objects?  From what I can tell, it
> looks like I need to use "Person.objects.extra()" to tie in the
> additional "where" statements.
>
> I apologize in advance if I've missed something obvious.  New to
> Django and just looking for help.
> >
>

--~--~---------~--~----~------------~-------~--~----~
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?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to