简体   繁体   English

Django查询多对一关系,如何检索多对一关系的数据

[英]Django query for many to one relationship, how to retrive data many to one relationship

how to retrive data many to one relationship.如何检索多对一关系的数据。

class Ads(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=75)

class Aimage(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    ads = models.ForeignKey(Ads, on_delete=models.CASCADE, related_name='ads_image')
    image = models.ImageField(blank=True)

my view:我的看法:

qs = Ads.objects.all()

template:模板:

{% for o in qs.aimage_set.all %}
{{ o.title }} 
{{ o.image.url }} #does work
{% endfor %}

qs is a set of Ads , so you can not access qs.aimage_set on the queryset but on an Ads model. qs是一Ads ,所以你不能访问qs.aimage_set查询集,但上一个Ads模式。 Furthermore you specified as value for the related_name=… parameter [Django-doc] , related_name='ads_image' , so this it the name of the manager to access the objects in reverse:此外,您指定了related_name=…参数 [Django-doc] 的值related_name='ads_image' ,因此它是反向访问对象的管理器名称:

{% for ad in qs %}
    <b>{{ o.title }}</b>
    {% for o in ad.ads_image.all %}
        {{ o.image.url }}
    {% endfor %}
{% endfor %}

This will result in an N+1 problem.这将导致N+1问题。 You can use .prefetch_related(…) [Django-doc] to fetch the related Aimage objects in bulk :您可以使用.prefetch_related(…) [Django-doc]批量获取相关的Aimage对象:

qs = Ads.objects.prefetch_related('ads_image')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM