Answer the question
In order to leave comments, you need to log in
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>
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>
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. Answer the question
In order to leave comments, you need to log in
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 :(
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 :(
Try all the same get_or_create + unique_together on the fields for which you are doing get_or_create
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/
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 questionAsk a Question
731 491 924 answers to any question