Why other model name treated as field name in filter in django during joining two table?

I am new at django.I stuck in a strange problem is that during joining two table foreign model name is treated as field name even i am using __ underscore and i am getting error. This is my two model :-

 class TD_FD(models.Model):
   id = models.BigAutoField(primary_key=True,db_index=True)
   identity=models.CharField(max_length=25,unique=True,db_index=True)
   del_status=models.CharField(max_length=6,default='na',db_index=True)
   status=models.CharField(max_length=16,db_index=True)
   primary_id=models.ForeignKey('all_scheme',to_field='identity',
   db_column='primary_id'
   ,on_delete=models.PROTECT,max_length=25,
   db_index=True)
   
   def __str__(self):
     return self

 class all_scheme(models.Model):
   id = models.BigAutoField(primary_key=True,db_index=True)
   identity=models.CharField(max_length=25,unique=True,db_index=True)
   del_status=models.CharField(max_length=6,default='na',db_index=True)
   status=models.CharField(max_length=16,db_index=True)
   scheme_name=models.CharField(max_length=150,db_index=True)
   branch_id=models.CharField(max_length=25,db_index=True)
   
   def __str__(self):
     return self

    ```
This is my query
`deposit_data=TD_FD.objects.filter(all_scheme__branch_id=branch_id).values()`
But .filter('all_scheme__branch_id' treated as field name.Why? 

   

Model TD_FD does not have anything while calling all_scheme. You can try calling that though:

deposit_data=TD_FD.objects.filter(primary_id__branch_id=branch_id).values()

Firstfully you have to specify field or relation. Since your TD_FD has a ForeignKey to all_scheme that you named primary_id, then you have to use that name. But filtering in that way seems pointless, because it will ALWAYS be one object, because it's ForeignKey (ManyToOne relationship).

Readm more about Django's relationships.

Back to Top