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.
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.
- [Answered ]-Cant find module Django while deploying on Elastic Beanstalk
- [Answered ]-What do you think about my Django model structure?
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
- [Answered ]-Django: Setting initial vals of multiplechoicefield only works first time
- [Answered ]-Django TemplateDoesNotExist and BASE_DIRS
- [Answered ]-Vagrant – Django server – Why is host redirecting to https?
- [Answered ]-Django is not displaying the image via /media/