Django形成了intergrityerror:具有唯一字段的外键,唯一约束失败

时间:2017-06-20 20:16:31

标签: python django python-3.x

当尝试使用ModelForm和CreateView添加具有dayplan外键的第二个约会(同一日期)时,由于DayPlan将“date”字段设置为唯一,因此唯一约束失败。

使用django-admin创建表单时,此问题不存在。

我尝试从dayplan.date中删除unique = True,看看会发生什么 - >每次我添加约会时,即使存在dayplan.date,也会创建一个新的日程安排。

问题似乎与这两行有关:

    daydate = DayPlan.objects.filter(date=planned_date)
    form.cleaned_data['dayplan'] = daydate

代码在这里:

class DayPlan(models.Model):
    date = models.DateField(unique=True, db_index=True)
    comment =  models.TextField(null=True, blank=True)

    def __str__(self):
        return 'Planning voor {}'.format(self.date)

    def get_absolute_url(self):
        return reverse('organizer_dayplan_detail', kwargs={'pk': self.pk})

class Appointment(models.Model):
    comment = models.CharField(null=True, blank=True, max_length=255)
    planned_date = models.DateField()
    doctor = models.ForeignKey(Doctor)
    visited = models.BooleanField(default=False)
    dayplan = models.ForeignKey(DayPlan)

class AppointCreate(CreateView):
    model = Appointment
    form_class = AppointmentForm
    template_name = 'organizer/organizer_appointment_create.html'
    # initial = {'doctor': 'pk', 'comment': 'test',}
    def get_initial(self):
        return {
            "doctor": self.request.GET.get('doctor')
        }

    def form_valid(self, form):
        planned_date = form.cleaned_data['planned_date']
        try:
            daydate = DayPlan.objects.filter(date=planned_date)
            form.cleaned_data['dayplan'] = daydate
            form.instance.save()


        except:
            daydate = DayPlan.objects.create(date=planned_date)
            form.instance.dayplan = daydate
            form.instance.save()
        return super(AppointCreate, self).form_valid(form)

class AppointmentForm(forms.ModelForm):
    class Meta:
        model = Appointment
        fields = {'comment', 'planned_date', 'doctor', 'visited', 'dayplan'}
        widgets = {'visited': forms.HiddenInput(),}
        exclude = {'dayplan',}

P.S。我确实意识到我不需要在这里使用“form.instance.save()”。删除它们没有效果。

提前致谢!

1 个答案:

答案 0 :(得分:1)

解决

daydate, created = DayPlan.objects.get_or_create(date=planned_date)
form.instance.dayplan = DayPlan.objects.get(date=planned_date)