I have a model like the following:
class Foo(models.Model):
fruit = models.CharField(max_length=10)
stuff = models.CharField(max_length=10)
color = models.CharField(max_length=10)
owner = models.CharField(max_length=20)
exists = models.BooleanField()
class Meta:
unique_together = (('fruit', 'stuff', 'color'), )
It is populated with some data:
fruit stuff color owner exists
Apple Table Blue abc True
Pear Book Red xyz False
Pear Phone Green xyz False
Apple Phone Blue abc True
Pear Table Green abc True
I need to merge/join this with a collection (not a queryset):
[('Apple', 'Table', 'Blue'), ('Pear', 'Phone', 'Green')]
So basically rows 0 and 2 should return when I search this model with this list of tuples.
Currently my workaround is to read Foo.objects.all()
into a DataFrame and do a merge with the list of tuples and get the ID's to pass to Foo.objects.filter()
. I also tried iterating over the list and calling Foo.object.get()
on each tuple but it is very slow. The list is quite big.
When I tried chaining Q's as suggested by the current answers, it threw an OperationalError (too many SQL variables).
My main goal is the following:
As it can be seen from the model these three fields together form my primary key. The table contains around 15k entries. When I get data from another source I need to check if the data is already in my table and create/update/delete accordingly (new data may contain up to 15k entries). Is there a clean and efficient way to check if these records are already in my table?
Note: The list of tuples does not have to be in that shape. I can modify it, turn it into another data structure or transpose it.