In a Django project as models I have something like that:
class Company(models.Model):
name = models.CharField(_(u"Name"), max_length=100)
INPUT_TYPES = (('U', _(u"User")), ('A', _(u"Administrator")))
class CompanyData(models.Model):
company = models.ForeignKey(Company, related_name='data')
input_type = models.CharField(_(u"Input type"), max_length=2,
choices=INPUT_TYPES)
active = models.BooleanField(_(u"Active"))
datafield_1 = models.CharField(_(u"Data field 1"), max_length=100)
datafield_2 = models.CharField(_(u"Data field 2"), max_length=100)
datafield_3 = models.CharField(_(u"Data field 3"), max_length=100)
The company data can be entered as a user or as an administrator.
It is possible to make searches on companies. The searches can be made without dealing with the input type but I want to exclude inactive company (no matter if it was set inactive by a user or by an administrator). I have tried a query like that:
Company.objects.filter(data__data_1='query string'
).exclude(Q(data__active=False))
But if one of the data input is active and match the query string it will return the company even if the other data input is inactive. I have tried to sophisticate the request by forcing the input type but I have found no manner to force Django to make two different join statements on the CompanyData table.
Congratulations, you have hit on one of the weaknesses of Django’s ORM. It is not possible to perform this sort of query with object syntax; you will need to resort to raw queries in order to accomplish this.