1

Noob Django ORM question here:

I have a model similar to this:

class Company(models.Model): id = models.PositiveIntegerField(null=False, blank=False, primary_key=True) name = models.CharField(max_length=255, null=True, blank=True, default="") class Audited(models.Model): company = models.ForeignKey( Company, null=False, blank=False, on_delete=models.CASCADE, related_name="logs" ) city = models.CharField(null=False, blank=False, max_length=255) 

I have been scratching my head with this problem and I can not figure out how to solve it.

Given a city, I need the company that do not have been audited on that city, so basically the Company who does not have a record on Audited with that city.

So for example, if the city is New York, and there is no record in Audited with a company like Oracle and city as New York, I receive Oracle.

It is very confusing to me because the ORM appears to have been designed for positive relations, like "the item from table A who has a record on Table B", and this is precisely the opposite. Any clue of how can I do this?

3
  • I assume there can be multiple copanies? Commented Sep 10, 2020 at 0:49
  • Yes, there can be multiple companies, but I always will need the first one, because after that I will add the row to Audited (for example, Oracle-New York), so the next time I asked for the next company to audit on New York, Oracle will be ignored. After the table is full (all the companies have records in New York, for example), I have to use other logic (the company audited on that city with the oldest date) Commented Sep 10, 2020 at 0:52
  • You should remove the id field from Company model as django creates one automatically. Commented Sep 10, 2020 at 2:21

1 Answer 1

1

You can filter with .exclude(…) [Django-doc]:

Company.objects.exclude(logs__city=my_city)

So you will retain Companys for which no Audited exists for the given my_city.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.