Home > OS >  how to get attribute from other model in your django template
how to get attribute from other model in your django template

Time:01-17

SO I have these two models, One is Members other is PaymentDetail. What I want is all the members from Member model in my template which I can get from Members.object.all() but also I want the payment_status of all those members in my template next to them. I dont know how to do it as payment_status is not in the Member model.

class Members(models.Model ):
    user = models.ForeignKey(Users,verbose_name='User Id', on_delete=models.CASCADE)
    com = models.ForeignKey(Committees, on_delete=models.CASCADE,verbose_name='Committee Name')
    mem_status = models.CharField( max_length=20,choices=MEMBER_STATUS, verbose_name='Member Status')
    mem_note = models.TextField(null=True, blank=True)

class PaymentDetails(models.Model):
    mem = models.ForeignKey(Members,on_delete=models.CASCADE, related_name="payment_details",verbose_name='Memeber Phone no')
    com = models.ForeignKey(Committees, on_delete=models.CASCADE,verbose_name='Committee Name')
    payment_month = models.DateField(default=datetime.now())
    payment_amount_debit = models.IntegerField(null=True,blank=True)
    payment_amount_credit = models.IntegerField(null=True,blank=True)
    payment_status = models.CharField(max_length=16, choices=PAYMENT_DETAILS_CHOICES, default="1")
    payment_proof = models.ImageField(upload_to='images/')
    payment_note = models.TextField(null=True,blank=True)

I searched alot and Found out there is somehting called related name and setname, but I am kinda new so I am not getting the desired results by using them too.

CodePudding user response:

Just use payment_details for each instance of Members like this:

members = Members.object.all()
for member in members:
    print(f"Member {member.id} has payment status of "  
          f"{member.payment_details.payment_status}")

member.payment_details gives you an instance of PaymentDetail and member.payment_details.payment_status is a payment_status field of PaymentDetail instance.

By the way, it's better to use singular form in model names.

CodePudding user response:

You can access to payment details object via a related name. I see you define payment_details so in HTML template you can access it by this:

member.payment_details.all()

There could be a performance issue because payment_details.all() will execute query to database. You can avoid this by using prefetch_related('payment_details') in django view. Exmaple:

Member.objects.prefetch_related('payment_details')

  •  Tags:  
  • Related