简体   繁体   中英

Django filter a queryset based on the template name

In my Django App, I have 2 models. One called Post and one called Categories. When a user clicks on a category, I want only the posts that are in that category to appear in the category detail view. For example if a user clicks on the medical category, I only want the posts in the medical category to appear.

Models:

class Category(models.Model):
    title = models.CharField(max_length=200)
    colorcode = models.CharField(max_length=20, blank=True, null=True)
    description = models.TextField()
    image = models.ImageField(blank=True, null=True)
    slug = models.SlugField(unique=True)

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    sub_description = models.TextField(blank=True, null=True)
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
    image = models.ImageField(blank=True, null=True)
    live = models.BooleanField(default=False)
    slug = models.SlugField(unique=True)

Views:

class CategoryDetailView(DetailView):
model = Category

def get_context_data(self, **kwargs):
    context = super(CategoryDetailView, self).get_context_data(**kwargs)
    context['category_posts'] = Post.objects.filter(live=True)
    return context

Template:

{% for post in category_posts %}
    <div class="post">
        <div class="post-title">
            {{ post.title }}
        </div>
        <div class="post-author">
            {{ post.author }}
        </div>
    </div>
{% endfor %}

In a DetailView , you have access to the actual object being rendered (in your case the Category instance) through self.object .

So in your get_context_data method you can do:

context['category_posts'] = Post.objects.filter(live=True, category=self.object)

Note that self.object might be None so you may want to deal with that case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM