Django - get in template reverse related many to many field -


i have 3 models, entry model , category model, , have created intermediate model categoryentry.

class entry(models.model):     entry_text = models.textfield()     user = models.foreignkey(user)  class category(models.model):     user = models.foreignkey(user)     category_text = models.charfield(max_length=200)     entries = models.manytomanyfield(entry, through='categoryentry')  class categoryentry(models.model):     category = models.foreignkey(category)     entry = models.foreignkey(entry)     viewed = models.booleanfield(default=false) 

i have created view get_queryset method this

    def get_queryset(self):     order_by = self.request.get.get('order_by')      if not order_by:         order_by = '-pub_date'      return entry.objects.filter(category__id=self.kwargs.get('category_id', none), category__user__id=self.request.user.id).order_by(order_by)[:].select_related('user') 

i have category id kwargs. problem - how every entries related field "viewed", can show value in template. example related user field can like

{% entry in entries %}     {{ entry.entry_text }}     {{ entry.user.name }} {% endfor %} 

what need access "viewed" field "entry.categoryentry.viewed"

tried prefetch_related, doesn't seem work or don't how know right name access field in template

entry.objects.filter(category__id=self.kwargs.get('category_id', none), category__user__id=self.request.user.id).order_by(order_by)[:].select_related('user').prefetch_related(prefetch("categoryentry_set", queryset=categoryentry.objects.filter(category__id=self.kwargs.get('category_id', none)))) 

thanks!

you do:

{% entry in entries %}     {{ entry.entry_text }}     {{ entry.user.name }}     {% ce in entry.catalogentry_set.all %}         {{ce.category.category_text}}          {# or whatever.. #}     {% endif %} {% endfor %} 

basically, if no related_name present, access reverse lookup element lowercase model name + _set - returns queryset manager object.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -