简体   繁体   中英

Django model with two foreign keys

I have the following models in django and I want to get in a queryset the customers of a specific salesman. That means that I want the customers that have at least one policy with a specific salesman.

class Salesman(models.Model):
      name = models.Charfield()

class Customer(models.Model):
      name = models.Charfield()

 class Policy(models.Model):
      policy_number = models.Charfield()
      salesman = models.Foreignkey(Salesman)
      customer = models.Foreignkey(Customer)

Can anyone help?

You can follow the foreign key backwards from customer to policy. Then use the double underscore to filter the salesman.

salesman = Salesman.objects.get(name="Loman")
Customer.objects.filter(policy__salesman=salesman).distinct()

The distinct() is required to prevent duplicates if the customer has more than one policy with that salesman.

See the docs on lookups that span relationships for more info.

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