0

I want to join two models as shown below and the join should be Harsha to Bank only(not Bank to 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

in templates

# 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 %}
0

1 Answer 1

1

You can get it like this(using reverse relationship):

{% for tes in test %}
    {{ tes.name }}
    {{ tes.email }}
    {% for bank in tes.bank_set.all %}
    {{ bank.accountnumber }}  
    {{ bank.ifsc }}  
    {% endfor %}
{% endfor %}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.