altunyurt
altunyurt

Reputation: 2936

Django: model.objects.create() changes the previous model.objects.filter()'s resultset

I have a simple model named Keyword:

class Keyword(models.Model):
    name = models.CharField(max_length=50, blank=False, null=False)

I'm trying to do bulk_create, but the bulk data may contain already existing keywords, therefore I do the operation in two steps. First fetch the existing keywords, then bulk_create new keywords. Following is a small example of what I do in the process:

In [12]: t = ["aaaa", "dene"]

In [16]: existing = Keyword.objects.filter(name__in=t).all()

In [17]: new = set(t).difference(list(existing.values_list("name", flat=True)))                                

In [18]: new
Out[18]: {'aaaa'}

In [19]: existing
Out[19]: [<Keyword: dene>]

In [20]: created = Keyword.objects.bulk_create([Keyword(name=name) for name in new])                           

In [21]: created
Out[21]: [<Keyword: aaaa>]

In [22]: existing
Out[22]: [<Keyword: aaaa>, <Keyword: dene>]

Both bulk_create and create updates the previous filter's resultset. This is most probably a bug, but I may also be missing some point here. Is there anything wrong in my implementation?

Django version is 1.5.3.

Upvotes: 1

Views: 283

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798536

Django querysets are evaluated lazily, when the values are actually retrieved. If you want to maintain the same sequence of models then you will need to pass them to e.g. the list constructor in order to firm them up.

existinglist = list(existing)

Upvotes: 2

Related Questions