Home > other >  pk reference in Django related models
pk reference in Django related models

Time:10-27

I am learning Django and doing some project where I have three models with following relationships:

#models.py

class Model1(models.Model):
   status = models.CharField(max_length = ....)

class Model2(models.Model):
   model1 = models.ForeignKey(Model1, ....)
   name = models.CharField(max_length = ....)

class Model3(models.Model):
   model2 = models.ForeignKey(Model2, ....)
   name = models.CharField(max_length = ....)

I want to update status field in my Model1 based on the logic which happens in my views.py on Model3 instance i.e.

views.py

def model3_view(request, pk):

   model1 = get_object_or_404(Model1, pk=pk)

   model3 = Model3.objects.filter(model1_id=model1.pk)

   my logic goes here....

   if <my logic outcome> == True:

      model1_status = Model1.objects.update_or_create(status='closed', pk=model1.pk)

However, I am getting error UNIQUE constraint failed: model1_model1.id.

I tried to reference my model2 instance pk and it does work fine i.e. model1_status = Model1.objects.update_or_create(status='closed', pk=model2.pk) but could not figure out how I can do this for 1 level up i.e. for model1 pk...

CodePudding user response:

The Unique error is most likely because the update_or_create is just trying to create and then getting conflicting primary keys.

Because you are already getting Model1 here: model1 = get_object_or_404(Model1, pk=pk) you could just replace the update_or_create with:

model1.status = 'closed'
model1.save()

Note: I didn't originally post this as an answer because I wasn't sure if update_or_create was mandatory or not.

  • Related