如何在Django模型中为反向关系的第一个活动项创建别名?
我有一个模型叫做 Item:
class Item(models.Model):
...
还有另一个模型叫做 Content。它和 Item 有关系,并且有一个选择字段用来选择内容是否是激活状态:
class Content(models.Model):
item = ForeignKey(Item related_name=)
is_active = BooleanField(default=False)
content = TextField()
def save(self, *args, **kwargs):
"""There's a logic to make sure every item has only one content"""
我有两个问题。
- 如何筛选出没有任何内容或者没有任何激活内容的 Item。
- 我可以做类似别名的操作来调用 item.content,以返回该 Item 的激活内容,而不影响数据库的性能吗?
1 个回答
0
如何过滤掉没有内容或者没有活跃内容的项目。
你可以通过以下方式进行过滤:
from django.db.models import Q
Content.objects.filter(~Q(content=''), is_active=True)
我可以用别名来调用 item.content,以返回项目的活跃内容,而不会影响数据库的性能吗?
相关名称看起来像这样:
class Content(models.Model):
item = ForeignKey(Item, on_delete=models.PROTECT, related_name='contents')
你可以通过以下方式预先获取这些 Content
到 contents
中:
from django.db.models import Prefetch, Q
Item.objects.prefetch_related(
Prefetch('contents', Content.objects.filter(~Q(content=''), is_active=True))
)
对于这些 Item
,它会将 .contents.all()
设置为相关的 Content
,其中 content
不为空,并且 is_active
为 True
。