Django duplicate key when trying to send a form with foreign key

ⅰ亾dé卋堺 提交于 2021-02-10 14:34:12

问题


I need to save a form with listaflor and multiple instances of flora2estado,When i try to send this form i get: IntegrityError at /enviar_flora/ (1062, "Duplicate entry '99-10031' for key 'PRIMARY'")

views.py:

def CreateFlo(request):
    form = FloForm()
    if request.method == 'POST':
        form = FloForm(request.POST)
        if form.is_valid():
            listafor = form.save()
            estados = form.cleaned_data.get('estados')
            for estado in estados:
                Flora2Estado.objects.create(especie=listafor, estado= estado)
            # or you can use bulk_create: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#bulk-create
  
    return render(request,'accounts/enviar_flora.html')

models.py:

class Listaflor(models.Model):
    especie_id = models.AutoField(db_column="especie_id",primary_key=True)
    familia = models.ForeignKey(Familia, models.DO_NOTHING, db_column='familia_id', blank=True, null=True)
    Especie = models.CharField(db_column='especie', max_length=255, blank=True, null=True)
    class Meta:
        managed = True
        db_table = 'listaflor'

class Flora2Estado(models.Model):
    estado = models.ForeignKey(EstadosM, models.CASCADE)
    especie = models.ForeignKey(Listaflor, models.CASCADE,default=99999)
    flora2estado = models.AutoField(primary_key=True, default=99999)
    class Meta:
        managed = True
        db_table = 'flora2estado'
        unique_together = (('estado', 'especie'),)


class EstadosM(models.Model):
    estado_id = models.AutoField(primary_key=True)
    estado_nome = models.CharField(max_length=100, blank=True, null=True)
    nome_abbr = models.CharField(max_length=2, blank=True, null=True)
    criadoem = models.DateTimeField(db_column='criadoEm')
    class Meta:
        managed = False
        db_table = 'estados'
    def __str__(self):
        return self.estado_nome

来源:https://stackoverflow.com/questions/66071889/django-duplicate-key-when-trying-to-send-a-form-with-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!