Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you have a category instance in template:</p> <pre><code>category.entry.all -&gt; list of entries </code></pre> <p>If you have an entry instance in template:</p> <pre><code>entry.category_entry.all -&gt; list of categories </code></pre> <p>You should call M2M fields in plural form, then you will have a more readable code</p> <pre><code>category.entries.all </code></pre> <p>%model%_set syntax (or related name, if you've specified it) is using to access to model trough a backward relationship.</p> <p><a href="https://docs.djangoproject.com/en/1.4/topics/db/queries/#following-relationships-backward" rel="nofollow">https://docs.djangoproject.com/en/1.4/topics/db/queries/#following-relationships-backward</a></p> <p><em>But how do I get the 'votes' associated with the m2m instance? – Bryce</em></p> <p>I suggest you the following way:</p> <pre><code>class Category(models.Model): title = models.CharField(max_length=1024,null=True,blank=True) entries = models.ManyToManyField(Entry,null=True,blank=True, related_name='categories', through='CategoryEntry', ) class CategoryEntry(models.Model): category = models.ForeignKey(Category, related_name='category_entries') entry = models.ForeignKey(Entry) votes = models.IntegerField(null=False, default=0) def category_detail(request, pk): category = models.Category.objects.select_related().get(pk=pk) category_entries = category.category_entries.filter(entry__temp_sort_order__gte=0).order_by('-entry__temp_sort_order') for category_entry in category_entries: # category_entry is an instance of the model CategoryEntry pprint('category entry votes: ' + str(category_entry.votes)) pprint('entry title: ' + category_entry.entry.title) .... HOW TO entry = Entry.objects.get(pk=1) entry.categories.all() # list of categories (here we work through related name of the field entries) category = Category.objects.get(pk=1) category.entries.all() # list of entries (here we work through m2m field entries) category.category_entries.all() # list of CategoryEntry objects (through related name category_entries of the field category in model CategoryEntry) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload