Django:无法创建与一个普通模型具有一对一关系的多个模型对象

问题描述 投票:0回答:1

我有两个模型,用模型和用户之间的auth.models.User关系扩展django的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和一个worker,但它创建了WorkerEmployer对象。

附:我的表格类是:

class WorkerSignUpForm(UserCreationForm):
    address = forms.CharField(max_length=400)

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')

django django-models
1个回答
0
投票

这是因为您正在关联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字段设为可选字段。

# models.py
class Worker(models.Model):
    address = models.CharField(max_length=400)
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True
)


class Employer(models.Model):
    address = models.CharField(max_length=400)
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True
)
© www.soinside.com 2019 - 2024. All rights reserved.