我的模特是这样的。
class Subscriber(models.Model):
skillset = models.TextField(verbose_name='Skill Set')
slug = models.SlugField(unique=True, default='')
class SoloDeveloper(models.Model):
first_name = models.CharField(max_length=30, verbose_name='First Name')
last_name = models.CharField(max_length=30, verbose_name='Last Name')
subscriber = models.OneToOneField(Subscriber, related_name='solo_dev', on_delete=models.CASCADE)
我正在尝试保存独奏开发人员并将其分配给订阅者的一对一字段。
def solo_dev_edit(request, slug):
subscriber = Subscriber.objects.get(slug=slug)
subscriber_form = SubscriberForm()
solo_dev_form = SoloDevForm()
if request.method == 'POST':
subscriber_form = SubscriberForm(data=request.POST, instance=subscriber)
solo_dev_form = SoloDevForm(data=request.POST)
if all[subscriber_form.is_valid(), solo_dev_form.is_valid()]:
sub = subscriber_form.save(commit=False)
solo_dev = solo_dev_form.save()
sub.solo_dev = solo_dev
sub.save()
return redirect('solo_dev_view', slug=subscriber.slug)
else:
subscriber_form = SubscriberForm()
solo_dev_form = SoloDevForm()
return render(request, 'main/solo_dev_edit.html', {
'sub_fm': subscriber_form,
'solo_dev_fm': solo_dev_form,
})
这说不清楚
列中的空值" subscriber_id"违反非空约束
DETAIL:失败的行包含(9,john,doe,null)。
我做错了什么?
答案 0 :(得分:2)
subscriber
上的SoloDeveloper
字段不允许空值。并且您尝试在SoloDeveloper
之前保存Subscriber
- 意味着subscribed_id
(订阅者的ID)将为None
,从而导致错误。
试试这个:
sub = subscriber_form.save()
solo_dev = solo_dev_form.save(commit=False)
solo_dev.subscriber = sub
solo_dev.save()
答案 1 :(得分:0)
想到订户没有被保存,所以我保存了solo dev,直到订阅者被保存。这有帮助。
sub = subscriber_form.save(commit=False)
solo_dev = solo_dev_form.save(commit=False)
sub.solo_dev = solo_dev
sub.save()
solo_dev.save()