[Answered ]-How to compare Specific value of two different tables in django?

1đź‘Ť

âś…

Something like this should work:

Contact.objects.exclude(
    id__in=Subscriber.objects.all()
).values_list('id', flat=True)

Note that these are actually two SQL queries. I’m sure there are ways to optimize it, but this will usually work fine.

Also, the values_list has nothing to do with selecting the objects, it just modifies “format” of what is returned (list of IDs instead of queryset of objects – but same database records in both cases).

If you are excluding by some field other then Subscriber.id (e.g: Subscriber.quasy_id):

Contact.objects.exclude(
    id__in=Subscriber.objects.all().values_list('quasy_id', flat=True)
).values_list('id', flat=True)

Edit:

This answer assumes you don’t have a relationship between your Contact and Subscriber models. If you do, then see @navit’s answer, it is a better choice.

Edit 2:

That flat=True inside exclude is actually not needed.

👤frnhr

1đź‘Ť

I assume you have your model like this:

class Subscriber(models.Model):
    contact = models.ForeignKey(Contact)

You can do what you want like this:

my_list = Subscriber.objects.filter(contact=None)

This retrieves Subscribers which don’t have a Contact. Retrieveing a list of Contacts is straightforward.

👤navid

0đź‘Ť

If you want to compare value of fields in two different tables(which have connection with ForeignKey) you can use something like this:

I assume model is like below:

class Contact(models.Model):  
 name = models.TextField()
 family = models.TextField()

class Subscriber(models.Model):
 subscriber_name = models.ForeignKey(Contact, on_delete=models.CASCADE)
 subscriber_family = models.TextField()

this would be the query:

query = Subscriber.objects.filter(subscriber_name =F(Contact__name))
return query
👤bghad1

Leave a comment