首页 > 解决方案 > 如何包含相关模型 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的信息。感谢任何帮助,谢谢。ImageAlbumProduct

标签: djangodjango-models

解决方案


我不确定,但我认为你会这样做:

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 %}

推荐阅读