[Answer]-Django querying from 3 models

1👍

First of all – python naming convention state that classes should not have underscores and prefer upper-case letters instead. So your models should be SourceEnquiry, Customer (not plural) and SaleCycle.

That being said, let’s say I have a SourceEnquiry item (I’m going to pick one arbitrarily), and you want all related SaleCycle items, you do it like so:

>>> sinq = SourceEnquiry.objects.get(pk=1)
>>> SaleCycle.objects.all().filter(customer_name__customer_src_n_type=sinq)

p.s.

also, going back to the naming convention thing, it’s redundant to use customer as part of a field name inside the class Customer. You alread know it’s a customer object, so it’s better to name it like so:

class Customer(models.Model):
    name = models.CharField(max_lentgth=200) 
    src_n_type = models.Foreign_key(source_of_enquiry)
    contact = models.CharField(max_lentgth=200)

You other fields can also be cleaner:

class SourceEnquiry(models.Model):
    value = models.CharField(max_length=200, null=True, blank=True)

class SaleCycle(models.Model):
    item = models.CharField(max_length=200) 
    customer = models.Foreignkey(Customer)
👤yuvi

Leave a comment