Django使用ORM基于联接从数据库中获取数据

时间:2019-07-04 05:58:21

标签: django django-models

我想加入两个模型,如下所示,并且加入的对象应该仅是Harsha到Bank(而不是Bank到Harsha)

model.py

class Harsha(models.Model):

    name = models.CharField(max_length=255)
    email = models.CharField(max_length=255)


class Bank(models.Model):

    user = models.ForeignKey(Harsha, on_delete=models.CASCADE)
    accountnumber = models.BigIntegerField()
    ifsc = models.CharField(max_length=255)
    branch = models.CharField(max_length=255)
    bank = models.CharField(max_length=255)

views.py

test = Harsha.objects.all()
test1 = Bank.objects.all() # its working for me but i want join from Harsha table

在模板中

# I want this
{% for tes in test %}
    {{ tes.name }}
    {{ tes.email }}
    {{ tes.bank.accountnumber }}  # how can I get this field
    {{ tes.bank.ifsc }}  # how can I get this field
{% endfor %}

# its working
{% for tes in test1 %}
    {{ tes.user.name }}
    {{ tes.user.email }}
    {{ tes.accountnumber }}
    {{ tes.ifsc }}
{% endfor %}

1 个答案:

答案 0 :(得分:1)

您可以这样获得(使用reverse relationship):

{% for tes in test %}
    {{ tes.name }}
    {{ tes.email }}
    {% for bank in tes.bank_set.all %}
    {{ bank.accountnumber }}  
    {{ bank.ifsc }}  
    {% endfor %}
{% endfor %}