Django - get_or_create not working

Can you help me understand why this code causes a duplicate entry (IntegrityError)?

I am on Django 1.2.

(row, is_new) = MyModel.objects.get_or_create(field1=1) row.other_field = 2 row.save() 

I have a unique restriction on field1. If there is a line where field1 = 1, everything works fine, Django does a "get".

If there is no line where field1 = 1, it looks like Django is creating this line, which is fine. But why does this not allow me to keep it?

Update:

If this helps, here is MyModel:

 class MyModel(models.Model): id = models.BigIntegerField(primary_key=True) field1 = models.BigIntegerField(unique=True) other_field = models.CharField(max_length=765) class Meta: db_table = u'project_crosses_suppl_FO' 

field1 is a foreign key to another table. But I did not make a model in Django for this table, so I am not telling Django about this foreign key.

+6
source share
3 answers

Assuming a reasonably correct representation of your real code, it is not surprising that this is not the Django that came out, this is your model.

You redefined the automatic primary key field with your own id field, but did not take into account its auto-increment. Thus, the database does not use the new value for the PC, and hence the integrity error.

If you have a really good reason, you should let Django deal with the PK field itself.

+7
source

get_or_create sounds to me. I'm just doing this job:

 rows = MyModel.objects.filter(field1=1) row = rows[0] if rows else MyModel(field1=1) row.other_field = 2 row.save() 
+3
source

Get or Create returns a tuple of results, even if your field that you use is specified as primary or unique.

So, in your case: row is a tuple with a single object, so this should work for you:

 (row, is_new) = MyModel.objects.get_or_create(field1=1) row[0].other_field = 2 row[0].save() 
+1
source

Source: https://habr.com/ru/post/895267/


All Articles