在这种情况下如何制作 Q 对象表达式(通过 ForeignKey 字段过滤)?
How to make Q object expression in this case(filtering by ForeignKey field)?
models.py:
class Post(models.Model):
title = models.TextField(max_length=1000, null=True, blank=True, default=None)
created = models.DateTimeField(auto_now_add=True)
class PostFollow(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
从那些模型 类 中,我想获得一些用户没有关注的帖子。
像这样:
user = User.objects.get(pk=1)
not_followed_post = Post.objects.filter(Q(pk__lte=1000) & ~Q(self__is_not_followed_by_user=user))
我该怎么做?
我认为使用 .exclude(..)
时更容易解释:
not_followed_post = Post.objects.exclude(
<b>postfollow__user=user</b>
).filter(
pk__lte=1000
)
.exclude(..)
将以透明的方式执行通用量化。
我认为在这里添加明确的 related_name
可能更好,这样可以更容易地查明关系正在查看的位置。例如:
class PostFollow(models.Model):
post = models.ForeignKey(
Post,
on_delete=models.CASCADE,
null=True,
blank=True,
<b>related_name='postfollow'</b>
)
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
null=True,
blank=True,
<b>related_name='postfollow'</b>
)
pk__lte
有点奇怪。通常 pk
仅用作标识符。像 __lte
这样的查询当然是可能的,但并不常见。
是的,pk
的创建顺序通常是 "distributed"(前提是您没有明确指定一个),因此如果您从不明确指定,您可能可以使用它来获取更新的记录比给定的记录。但我仍然认为以这种方式开始过滤有点"risky"。例如,如果您稍后将 historical 数据添加到数据库,那么这些数据(取决于您插入数据的方式)可以具有更高的 id
s,从而显示在结果中.
models.py:
class Post(models.Model):
title = models.TextField(max_length=1000, null=True, blank=True, default=None)
created = models.DateTimeField(auto_now_add=True)
class PostFollow(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
从那些模型 类 中,我想获得一些用户没有关注的帖子。
像这样:
user = User.objects.get(pk=1)
not_followed_post = Post.objects.filter(Q(pk__lte=1000) & ~Q(self__is_not_followed_by_user=user))
我该怎么做?
我认为使用 .exclude(..)
时更容易解释:
not_followed_post = Post.objects.exclude(
<b>postfollow__user=user</b>
).filter(
pk__lte=1000
)
.exclude(..)
将以透明的方式执行通用量化。
我认为在这里添加明确的 related_name
可能更好,这样可以更容易地查明关系正在查看的位置。例如:
class PostFollow(models.Model):
post = models.ForeignKey(
Post,
on_delete=models.CASCADE,
null=True,
blank=True,
<b>related_name='postfollow'</b>
)
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
null=True,
blank=True,
<b>related_name='postfollow'</b>
)
pk__lte
有点奇怪。通常 pk
仅用作标识符。像 __lte
这样的查询当然是可能的,但并不常见。
是的,pk
的创建顺序通常是 "distributed"(前提是您没有明确指定一个),因此如果您从不明确指定,您可能可以使用它来获取更新的记录比给定的记录。但我仍然认为以这种方式开始过滤有点"risky"。例如,如果您稍后将 historical 数据添加到数据库,那么这些数据(取决于您插入数据的方式)可以具有更高的 id
s,从而显示在结果中.