django - How do I exclude current object in ManyToMany query? -


i have 2 basic models, story , category:

class category(models.model):     title = models.charfield(max_length=50)     slug = models.slugfield()     ...  class story(models.model):     headline = models.charfield(max_length=50)     slug = models.slugfield()     categories = models.manytomanyfield(category)     ... 

and view story detail:

from django.views.generic import date_based, list_detail solo.apps.news.models import story  def story_detail(request, slug, year, month, day): """ displays story detail. if user superuser, view display  unpublished story detail previewing purposes. """ stories = none if request.user.is_superuser:     stories = story.objects.all() else:     stories = story.objects.live() return date_based.object_detail(     request,     year=year,     month=month,     day=day,     date_field='pub_date',     slug=slug,     queryset=stories,     template_object_name = 'story', ) 

on view given story object -- i'm using generic detail view -- i'd display list of stories related current story via categories applied current story.

here's how i'm doing in story detail template:

{% category in story.category.all %}     <ul id="related_stories">     {% story in category.story_set.all|slice:"5" %}         <li><a href="{{ story.get_absolute_url }}" title="{{ story.headline }}">{{ story.headline }}</a></li>     {% endfor %}     </ul> {% endfor %} 

this provides me need except i'd avoid displaying linked headline story i'm viewing currently.

i believe done via "exclude" filter, i'm not sure if belongs on category or story model method, or how construct it.

any appreciated!

do this:

class story(models.model): ...    @property    def related_story_set(self):        category_id_list = self.category.values_list("id", flat=true)        return story.objects.filter(category__id__in=category_id_list).exclude(id=self.id) 

then can in template:

<ul id="related_stories"> {% related_story in story.related_story_set.all|slice:"5" %}     <li><a href="{{ related_story.get_absolute_url }}" title="{{ related_story.headline }}">{{ related_story.headline }}</a></li> {% endfor %} </ul> 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -