首页 > 解决方案 > Django Query 查询中对象的第一个 ForeignKey

问题描述

尝试按距离对有序商店实例进行查询,然后查询每个商店实例的第一个 Foreignkey Coupon。我正在尝试展示附近每个商店的优惠券。

位置通过 GeoDjango 工作正常,我的问题是查询

模型.py

...
class Store(models.Model):
   location = models.PointField(srid=4326, null=True, blank=True)


class Coupon(models.Model):
    store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, related_name='coupon')
    title = models.CharField(max_length=255)

视图.py

class homeView(View):

    def get(self, *args, **kwargs):

       store_nearby = Store.objects.annotate(distance = Distance("location", user_location)).order_by("distance")

    context = {
        'store_list': store_nearby,
        # 'offer': offer,
    }
    return render(self.request, 'mysite/home_page.html', context)

home_page.html

{% for object in store_list %}
    {% for coupon in object.coupon.first %} // This doesnt work
        {{ coupon.title }}
    {% endfor %}
{% endfor %}

标签: django

解决方案


也许你可以这样尝试:

{% for object in store_list %}
    {{ object.coupon.first.title }}
{% endfor %}

或者

像这样使用查询集添加标题(使用subquery):

from django.db.models import OuterRef, Subquery

...
coupons = Coupon.objects.filter(store=OuterRef('pk'))
store_nearby = Store.objects.annotate(distance = Distance("location", user_location)).annotate(coupon_title=Subquery(coupons.values('title')[:1])).order_by("distance")

并在模板中使用它:

{% for object in store_list %}
    {{ object.coupon_title }}
{% endfor %}

第二种解决方案非常理想,因为它将减少 DB 命中。


推荐阅读