Sam
Sam

Reputation: 388

How to filter objects in a class based view django

I have a class for a blog post detail like this:

class MaghaleDetail(DetailView):
    model = MaghaalaatPost
    template_name = 'Blog/Blog-elmi-detail.html'
    context_object_name = 'maghaale'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["related_items"] = self.object.tags.similar_objects()[:3]
        context["images"] = MaghaalaatImages.objects.all()
        return context

and this is my models:

class MaghaalaatPost(models.Model):
    title = models.CharField(max_length=250)
    paragraph = models.TextField(blank=True)
class MaghaalaatImages(models.Model):
    post = models.ForeignKey(MaghaalaatPost, default=None, 
        on_delete=models.CASCADE)
    images = models.FileField(upload_to='post_images', blank=True)

the images context shows every single image because I set it to all(). how do I filter it to show only the images to this specific post?

Upvotes: 2

Views: 404

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476624

You actually do not need to pass this to the context. If you define a relation (like a ForeignKey, OneToOneField, ManyToManyField, etc.), then Django will add a manager in the target model to access the related objects, you can thus access the related objects in the template with:

{% for image in maghaale.maghaalaatimages_set.all %}
    … do something with image …
{% endfor %}

For the name of the relation in reverse, you can specify the related_name=… parameter [Django-doc]. If you do not specify this, Django will use modelname_set with modelname the name of the class of the model in lowercase.

or in the context:

class MaghaleDetail(DetailView):
    model = MaghaalaatPost
    template_name = 'Blog/Blog-elmi-detail.html'
    context_object_name = 'maghaale'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['related_items'] = self.object.tags.similar_objects()[:3]
        context['images'] = self.object.maghaalaatimages_set.all()
        return context

Upvotes: 3

Related Questions