How to get result from manytomany?

4 views
Skip to first unread message

veasna bunhor

unread,
Oct 1, 2009, 3:49:02 AM10/1/09
to django...@googlegroups.com
I have two models :

class Individual(models.Model):
    name = models.CharField(max_length=200)
    is_author = models.BooleanField()
    active = models.BooleanField(default=True)
----------------------------------------------------------------------------------------------------
class Book(models.Model):
    title = models.CharField(max_length=200)
    authors = models.ManyToManyField(Individual, related_name="author_for", blank=True, null=True)
------------------------------------------------------------------------------------------------------------------

Can i make the query to get all the books that is_author?
 i have tried:
>>>authors = Individual.objects.filter(is_author=True).filter(active=True)
>>>for author in authors:
           print author.name
           for book in author.book_set.all():
                  print book.title

Anıl KARADAĞ

unread,
Oct 1, 2009, 4:06:06 AM10/1/09
to django...@googlegroups.com
Hi,

veasna bunhor yazmış:
> I have two models :
>
> class Individual(models.Model):
> name = models.CharField(max_length=200)
> * is_author = models.BooleanField()*
> active = models.BooleanField(default=True)
> ----------------------------------------------------------------------------------------------------
> class Book(models.Model):
> title = models.CharField(max_length=200)
> *authors = models.ManyToManyField(Individual,
> related_name="author_for", blank=True, null=True)*

you used related_name for model so you should call format similar to
author.author_for.all()

Q: What is meaning of "related_name" and how we use it?
A:
http://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name
> ------------------------------------------------------------------------------------------------------------------
>
> Can i make the query to get all the books that is_author?
> i have tried:
> >>>authors = Individual.objects.filter(is_author=True).filter(active=True)
> >>>for author in authors:
> print author.name <http://author.name>

veasna bunhor

unread,
Oct 1, 2009, 4:20:27 AM10/1/09
to django...@googlegroups.com
Thanks you very much. Now it's work.
Reply all
Reply to author
Forward
0 new messages