django - 如何包含相关模型 Django
问题描述
我有 3 个模型:
class ImageAlbum(models.Model):
def default(self):
return self.images.filter(default=True).first()
def thumbnails(self):
return self.images.filter(width__lt=100, length_lt=100)
class Image(models.Model):
name = models.CharField(max_length=255)
image = models.ImageField(upload_to='images/')
default = models.BooleanField(default=False)
width = models.FloatField(default=100)
length = models.FloatField(default=100)
album = models.ForeignKey(ImageAlbum, related_name='images', on_delete=models.CASCADE)
class Product(models.Model):
title = models.CharField(max_length=300)
price = models.IntegerField()
description = models.TextField(max_length=2000, help_text="This is the description of the product")
images = models.OneToOneField(ImageAlbum, related_name='model', on_delete=models.CASCADE)
当我选择产品型号时
Product.objects
在该Product
字段中images
,我只有专辑的主键。当我选择模型时,我想获得相关ImageAlbum
和所有相关Image
的信息。感谢任何帮助,谢谢。ImageAlbum
Product
解决方案
我不确定,但我认为你会这样做:
product = Product.objects.get(pk=pk) # query the product
images = product.images.default()
thumbnails = product.images.thumbnails()
因此,为了对许多产品执行此操作,您应该真正摆脱ImageAlbum
模型,因为它确实没有必要,您可以将图像与产品联系起来,那组图像将成为图像相册(有点)(如果你想存储缩略图,您可以为您的图像模型手动执行此操作(1 个对象中只有 2 个图像))
迁移之后,使用Prefetch来获取孩子:
from django.db.models import Prefetch
products = Product.objects.all()
images = Image.objects.prefetch_related(
Prefetch(
'images', # the related name
Product.objects.all(), # queryset
to_attr='product_images' # attribute for usage in the template
)
)
your_template.html
{% for product im products %}
{% for image in product.product_images %}
...
{% endfor %}
{% endfor %}
推荐阅读
- robocopy - powershell 的 Copy-Item 命令不适用于大文件
- windows - 从浏览器启动 i2 分析师笔记本
- python - 从 CSV 输入 Python 中查找最后一行
- javascript - 如果文件不存在,则无法使用 selenium (js) 将密钥发送到文件表单字段
- java - 使圆形按钮的外线更大
- scala - Spark-SQL 数据帧计数给出 java.lang.ArrayIndexOutOfBoundsException
- javascript - 试图使滚动到顶部按钮起作用
- reactjs - redux 官方 todo 示例中来自 mapStateToProps 的 Children 在哪里?
- c++ - 向注册表项添加值时遇到问题
- c# - MissingMethodException Global.asax.cs