在Django中根据布尔值从模型中排除行

vtwuwzda  于 2023-05-08  发布在  Go
关注(0)|答案(1)|浏览(181)

我有一个帖子模型和用户模型用户有一个个人资料页面,包含他们的信息和他们的帖子。Post模型是这样的:

# models.py
class Post(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
    title = models.CharField(max_length=255, verbose_name="Post Title")
    slug = models.SlugField(null=True, blank=True, unique=False)
    content = QuillField()
    topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True, blank=True)
    is_published = models.BooleanField(null=False, default=True)
    likes = models.ManyToManyField(User, related_name="post_likes", blank=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if self.slug is None:
            self.slug = slugify(self. Title)

        super().save(*args, **kwargs)
# views.py
class UserView(TemplateView):
    def get(self, request, username=None):
        if username == None:
            user = User.objects.get(username=request.user.username)
        else:
            user = User.objects.get(username=username)

        posts = Post.objects.filter(owner__username=username).all()

        context = {"user": user, "posts": posts}
        return render(request, "base/user_view.html", context)

用户可以创建帖子,但可以将其保存为草稿或发布。我想实现的是,用户去他们的个人资料,他们可以看到他们的所有职位已发布和已保存为草案,但其他用户只能看到该用户的已发布的职位。
如何在配置文件模板中实现这一点?或者可以在www.example.com上完成views.py?

bttbmeg0

bttbmeg01#

只需将发布的条件添加到过滤器:

posts_own = Post.objects.filter(owner__username=username)....
posts_others= Post.objects.exclude(owner__username=username).filter(is_published=True)....

相关问题