简体   繁体   中英

Django query does not select related_name

I do have the following models in 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')
    [...]

As you can see they are related with "related_name" definition in the InvoiceNumbers model.

When I no do a query in django like:

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

And iterate through this query in a template

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

I get the template error that pay_invoice_meta is not iterable. With a manual select statement including the left outer join I get all the results.

What am I missing here? How can I force the query to select the values from InvoiceNumbers?

Call the all method of the related object to return a QuerySet:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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