2017-06-20 61 views
0

当尝试添加使用ModelForm和CreateView具有dayplan外键的第二个约会(对于相同日期)时,由于DayPlan具有'date'字段是唯一的。Django表格intergrityerror:具有唯一字段的外键,唯一约束失败

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

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

问题似乎与这些2线:

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()”。去除它们没有效果。

在此先感谢!

回答

0

解决

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