无法保存相关对象

Unable to save related object

我有这样的模型。

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

这没有说明

null value in column "subscriber_id" violates not-null constraint
DETAIL: Failing row contains (9, john, doe, null).

我做错了什么?

您在 SoloDeveloper 上的 subscriber 字段不允许空值。并且您试图在 Subscriber 之前保存 SoloDeveloper——这意味着 subscribed_id(订户的 ID)将是 None,从而导致错误。 试试这个:

        sub = subscriber_form.save()
        solo_dev = solo_dev_form.save(commit=False)
        solo_dev.subscriber = sub
        solo_dev.save()

认为订阅者没有被保存,所以我将保存独奏开发搁置,直到订阅者被保存。这有帮助。

sub = subscriber_form.save(commit=False)
solo_dev = solo_dev_form.save(commit=False)
sub.solo_dev = solo_dev
sub.save()
solo_dev.save()