简体   繁体   中英

How to filter Django BooleanFields and display the results in a template

Brand new to Python/Django and have hit a wall trying to figure out how to only show posts marked as True in certain parts of the same template.

For eg. I have a blog, the User can make posts but I want the posts marked as science_post , using a Django BooleanField , to be displayed separately from the rest of the blog posts.

Here's what I have for my Post model:

class Post(models.Model):
    title = models.CharField(max_length=31)
    content = models.TextField()
    thumbnail = models.ImageField()
    picture_description = models.CharField(max_length=100, default=True)
    displayed_author = models.CharField(max_length=25, default=True)
    shortquote = models.TextField()
    reference_title = models.ManyToManyField(References)
    publish_date = models.DateTimeField(auto_now_add=True)
    last_updated = models.DateTimeField(auto_now=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    slug = models.SlugField()
    science_post = models.BooleanField(default=False)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("detail", kwargs={
            'slug': self.slug
        })

    def get_love_url(self):
        return reverse("love", kwargs={
            'slug': self.slug
        })

    @property
    def comments(self):
        return self.comment_set.all()

    @property
    def get_comment_count(self):
        return self.comment_set.all().count()

    @property
    def get_view_count(self):
        return self.postview_set.all().count()

    @property
    def get_love_count(self):
        return self.love_set.all().count()

My idea was to simply filter out the posts marked science_post in the template using something along the lines of

{% if science_post %}
SHOW SCIENCE POST CONTENT HERE
{% endif %}

...But this returns nothing. Any help or a point in the right direction with this would be great. And if any additional info is needed, please let me know. Thanks.

In order to realize two seperate displays of posts you should use two seperate queries in the backend instead of seperating them using if-statements in the frontend.

Try passing two QuerySets to your template, using two seperate queries where you filter the different kinds of posts:

...
science = Post.objects.filter(science_post=True)
non_science = Post.objects.filter(science_post=False)
...

And then render them seperately in your template:

...
{% for post in science_post %}
SHOW SCIENCE POST CONTENT HERE
{% endfor %}
...
{% for post in non_science %}
SHOW NON-SCIENCE POST CONTENT HERE
{% endfor %}
...

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