gpt4 book ai didi

python - Django表单完整性错误: foreign key with unique field,唯一约束失败

转载 作者:太空宇宙 更新时间:2023-11-03 15:05:59 25 4
gpt4 key购买 nike

当尝试使用 ModelForm 和 CreateView 添加具有日计划外键的第二个约会(同一日期)时,由于 DayPlan 的“日期”字段是唯一的,唯一约束失败。

使用 django-admin 创建表单不会出现此问题。

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

问题似乎与这两行有关:

    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',}

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

提前致谢!

最佳答案

已解决

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

关于python - Django表单完整性错误: foreign key with unique field,唯一约束失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44662255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com