Django查询不选择related_name

时间:2017-10-18 09:49:12

标签: python django django-queryset

我在django中有以下模型:

class UserPayments(models.Model):

    _DATABASE = "payments"

    id = models.AutoField(primary_key=True)
    paym_psp_id = models.ForeignKey(ConfigPSP, null=True, on_delete=models.SET_NULL)
    [...]

class InvoiceNumbers(models.Model):
    _DATABASE = "payments"

    id = models.AutoField(primary_key=True)
    inv_date = models.DateField(null=False)
    inv_payment_id = models.ForeignKey(UserPayments, null=True, on_delete=models.DO_NOTHING, related_name='paym_invoice_meta')
    [...]

如您所见,它们与InvoiceNumbers模型中的“related_name”定义相关。

当我没有在django中执行查询时:

payments = UserPayments.objects.filter(paym_user_id=user_id)

在模板中迭代此查询

{% for inv in payments %}
      {% for meta in inv.paym_invoice_meta %}
            {{ meta.inv_invoice_hash }}
      {% endfor %}
{% endfor %}

我收到 pay_invoice_meta 不可迭代的模板错误。使用包含左外连接的手动选择语句,我得到所有结果。

我在这里缺少什么?如何强制查询从InvoiceNumbers中选择值?

1 个答案:

答案 0 :(得分:0)

调用相关对象的all方法返回QuerySet:

{% for inv in payments %}
    {% for meta in inv.paym_invoice_meta.all %}
        {{ meta.inv_invoice_hash }}
    {% endfor %}
{% endfor %}