Home > database >  Django how to create object has foreignkey in views.py?
Django how to create object has foreignkey in views.py?

Time:02-21

I've wrote this code:

views.py

    if not null:
            Address.objects.create(user = request.user,first_name = ad,last_name = soyad,address_title = baslik,address = adres,postalcode = posta,tel = gsm,il_ilce = Ilce.objects.get(il_id__il = sehir,ilce = ilce))

models.py

class Il(models.Model):
    il = models.CharField(max_length=20,blank=False,null=False)
    def __str__(self):
        return str(self.il)

class Ilce(models.Model):
    ilce = models.CharField(max_length=20,blank=False,null=False)
    il_id = models.ForeignKey(Il,blank=False,null=False,on_delete=models.PROTECT)
    def __str__(self):
        return str(self.ilce)

class Address(models.Model):
    
    first_name = models.CharField(max_length=30,blank=False,null=False)
    last_name = models.CharField(max_length=30,blank=False,null=False)
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    address_title = models.CharField(max_length=20,blank=False,null=False,default="Adres")
    address = models.TextField(max_length=255,blank=False,null=False)
    il_ilce = models.ForeignKey(Ilce,blank=False,null=False,on_delete=models.PROTECT)
    postalcode = models.CharField(max_length=5,blank=False,null=False)
    tel = models.CharField(max_length=11,blank=False,null=False)

    def __str__(self):
        return str(self.user)   '-'   str(self.address_title)

but I'm getting this error:

duplicate key value violates unique constraint "Users_address_user_id_key"
DETAIL:  Key (user_id)=(1) already exists.

I don't want the code to create a new user object I want it to create a new address object only.

CodePudding user response:

I don't want the code to create a new user object I want it to create a new address object only. - You've used OneToOneField in your Address model which means each user will have one address associated with it if you try to create one more then it will raise given exception duplicate key value violates unique constraint "Users_address_user_id_key" so to solve this you can use
update_or_create(...) [Djnago-doc] or If you want to use multiple address against one use then you've to change OneToOneFiled to ForeignKey.

  • Related