Django:无法与一个常见模型建立一对一关系的多个模型对象

时间:2019-04-20 10:25:45

标签: django django-models

我有两个模型,它们通过django的auth.models.User在模型和用户之间的关系来扩展。我想使用表单创建这两个对象之一的对象。

两个模型是:

one-to-one

我有一个创建者视图功能,如下:

class Worker(models.Model):
    address = models.CharField(max_length=400)
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    @receiver(post_save, sender=User)
    def create_user_worker(sender, instance, created, **kwargs):
        if created:
            Worker.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user_worker(sender, instance, **kwargs):
        instance.worker.save()

class Employer(models.Model):
    address = models.CharField(max_length=400)
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    @receiver(post_save, sender=User)
    def create_user_employer(sender, instance, created, **kwargs):
        if created:
            Employer.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user_employer(sender, instance, **kwargs):
        instance.employer.save()

我希望数据库中有一个def worker_sign_up(request): if request.method == 'POST': form = WorkerSignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.employer = None user.worker = Worker() user.worker.address= form.cleaned_data.get('address') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('home') else: form = WorkerSignUpForm() return render(request, 'registration/workersignup.html', {'form': form}) 和一个user,但是它同时创建了workerWorker对象。

p.s。 我的表单类别是:

Employer

1 个答案:

答案 0 :(得分:0)

这是因为您要关联一个set(boolean)对象并保存Employer。代替使用User,而使用user.save()。这不会为user.worker.save()创建任何对象。

Employer

此外,您需要将#views.py def worker_sign_up(request): if request.method == 'POST': form = WorkerSignUpForm(request.POST) if form.is_valid(): user = form.save() #save the user user.worker = Collector() # not sure why you need this user.worker.address= form.cleaned_data.get('address') user.worker.save() # this will create an object for Worker only raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('home') else: form = WorkerSignUpForm() return render(request, 'registration/workersignup.html', {'form': form}) 字段设为可选。

OneToOne