顺便说一下,我是一个编程新手。一般的Django。我一直在自学。
在讨论这个问题之前,我先分享一下我的Django代码:
models.py:
class User(AbstractUser):
# DATABASE FIELDS
email = models.EmailField(("email address"), unique=True)
REQUIRED_FIELDS = ['username']
USERNAME_FIELD = 'email'
# META
class Meta:
verbose_name = "User"
verbose_name_plural = "Users"
# TO STRING METHOD
def __str__(self):
return "User " + str(self.id) + " - " + self.email
class UserProfile(models.Model):
# RELATIONSHIP
user = models.ForeignKey(
to = User,
on_delete = models.CASCADE,
related_name = "user_account"
)
# DATABASE FIELDS
first_name = models.CharField(max_length=100, verbose_name="First Name")
last_name = models.CharField(max_length=100, verbose_name="Last Name")
date_created = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Profile Created On")
role = models.CharField(max_length=255, verbose_name="User Demographic")
# META
class Meta:
verbose_name = "User Profile"
verbose_name_plural = "User Profiles"
# TO STRING METHOD
def __str__(self):
return self.first_name
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import User
class AbstractUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email')
class AbstractUserChangeForm(UserChangeForm):
class Meta:
model = User
fields = UserChangeForm.Meta.fields
serializers.py
from rest_framework import serializers
from djoser.serializers import UserCreateSerializer, UserSerializer
from . import models
from .models import User, UserProfile
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ('id', 'email', 'username', 'password')
class UserCreateSerializer(UserCreateSerializer):
class Meta(UserCreateSerializer.Meta):
model = User
fields = ('id', 'email', 'username', 'password')
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ("id", "user", "first_name", "last_name", "date_created", "role")
User(AbstractUser)
模型带有一些默认字段。我试图引用的两个默认字段是:
first_name
&last_name
我要做的是,让这两个默认字段与我的UserProfile
模型连接,这样,当我创建我的用户并填写这些字段时,它也会显示在我的UserProfile
中,而不必在那里填写它并将其与用户连接。
有没有人对如何实现这两个模型的连接/引用有任何建议?
(只是作为一个补充,我也使用React为我的前端框架,并有请求工作。直到现在我才意识到我需要在创建我的SignUp组件后连接这两个字段/模型。
默认情况下,ForeignKey
是关系的主键。但是我们也可以使用to_field
参数指向其他字段。
我还没有试过下面的代码。但是你可以在models.py
:
中这样做models.py
class UserProfile(models.Model):
# RELATIONSHIP
user = models.ForeignKey(
to = User,
on_delete = models.CASCADE,
related_name = "user_account"
)
# DATABASE FIELDS
first_name = models.ForeignKey(User, to_field="firstname_field", verbose_name="First Name")
last_name = models.ForeignKey(User, to_field="lastname_field", verbose_name="Last Name")
你可以在这里查阅文件。
您只需要在Userprofile
中声明为OnetoOneField
而不声明first_name
和last_name
,因为用户模型已经声明了这些字段
models.py
from django.contrib.auth import get_user_model()
class UserProfile(models.model):
user = models.OnetoOneField(get_user_model(), on_delete=models.CASCADE)