S
S
SilentSokolov2013-07-16 18:00:21
Django
SilentSokolov, 2013-07-16 18:00:21

ContentType Behavior?

models.py

class Tag(models.Model):<br>
    user = models.ForeignKey(User)<br>
    content_type = models.ForeignKey(ContentType)<br>
    object_id = models.PositiveIntegerField()<br>
    content_object = generic.GenericForeignKey('content_type', 'object_id')<br>

views.py
try:<br>
    obj = Tag.objects.get(user_id=user.id, content_type=obj_type, object_id=item_id)<br>
except ObjectDoesNotExist:<br>
    obj = Tag.objects.create(user_id=user.id, content_type=obj_type, object_id=item_id)<br>
....<br>
obj.save()<br>

A piece of code searches for an entry in the database and if it finds it, it updates it, if not, it creates a new one. You can write more briefly through get_or_create, but not the point. The bottom line is that with several iterations with the same values, it does not find a record and creates it again, then complains that it get()returns two objects. What does the moment of creating the second is random, it can be at the third iteration, maybe at the hundredth.
Django version 1.5, MySQL base, cache disabled. No matter how hard he fought (passed different values ​​to bare numbers and objects, instead of get using filter [0]), all the same, at the N-th iteration, he creates a double entry in the database: \
Where to dig?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
S
SilentSokolov, 2013-07-17
@SilentSokolov

I figured it out and found the culprit - muscle, namely InnoDB (by default for all created tables from version 5.5.5), if you use MyISAM, then everything falls into place and works correctly. The solution is not suitable for everyone ... but at least some :(

V
Vladimir Sokolovsky, 2013-07-16
@inlanger

And I thought we were the only ones. We have the same problem, and it's not entirely clear where it came from. And we haven't solved it yet :(

A
alz, 2013-07-17
@alz

Try all the same get_or_create + unique_together on the fields for which you are doing get_or_create

N
Nikita, 2013-07-18
@Nikita

You probably have problems with innodb's isolation type, the default is not what Django expects. There is a whole separate topic about the problem in detail: habrahabr.ru/post/144161/

H
homm, 2013-11-14
@homm

Apparently all your requests are executed in a transaction (there is such a setting in settings). And when 2 requests arrive at about the same time, they each open their own transaction and look at the entry in it. Both are not found. The difference between mayisam and innodb is that the former simply does not support transactions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question