【问题标题】:Is there a way to have multiple instances of a model embedded into a single model field in Django?有没有办法将模型的多个实例嵌入到 Django 中的单个模型字段中?
【发布时间】:2020-10-22 07:36:20
【问题描述】:
我知道外键概念,Djongo Array field ,但是还有其他选择吗?
外键概念的问题是我需要对数据库进行多次点击,而 Array 字段的问题是缺乏信息以及在没有已知解决方案的情况下出现的错误。
我想做的基本上是实际上将模型的多个实例添加到另一个模型中的单个字段中,但我想嵌入它而不是为我尝试使用抽象模型的 cmets 创建一个新表,但是它确实做到了不行。
我想知道任何替代解决方案。
【问题讨论】:
标签:
python
django
django-models
mongodb-query
foreign-keys
【解决方案1】:
您可以使用外键,并且为了避免对每条相关记录进行单独查询,您可以使用 prefetch_related - https://docs.djangoproject.com/en/3.1/ref/models/querysets/#prefetch-related 一次性提取它们:
返回一个 QuerySet,它将在单个批次中自动检索每个指定查找的相关对象。
代码示例:
# models.py
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
class Comment(models.Model):
post = models.ForeignKey(Post, models.CASCADE)
text = models.TextField()
# Somewhere else, fetch posts together with related comments:
# It will take 2 requests in total
# - one to fetch posts, another to fetch all related comments
for post in Post.objects.all().prefetch_related('comment_set'):
print([c.text for c in post.comment_set.all()])