django - 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 %}
解决方案
也许你可以这样尝试:
{% 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 命中。
推荐阅读
- python - 在 Python 中反转没有 Numpy 的矩阵
- wordpress - WordPress插件排队脚本不起作用
- junit5 - JUnit5 - ExpectedException.expectCause() 等效
- angular - Observables : 在新的订阅调用中取消之前的 http 请求
- android - 在 Firestore 中使用对象表示或字符串哪个更可靠
- javascript - Cloud Firestore 按子值搜索
- c++ - 无法从 Boost::mapped_file 读取:数据缓冲区为 NULL
- java - MockwebServer 不模拟 http 调用
- oracle - Laravel Passport Token 数据库创建错误
- prolog - Prolog中的打印格式问题