这是我的用户模型,
class User(AbstractBaseUser, PermissionsMixin, Base):
user_id = models.AutoField(primary_key=True)
email = models.EmailField(db_index=True, max_length=100, unique=True)
is_advisor = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
这是用户简介
class UserProfile(Base):
profile_id = models.AutoField(primary_key=True)
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile')
first_name = models.CharField(null=True, blank=True, max_length=100)
last_name = models.CharField(null=True, blank=True, max_length=100)
thumbnail = models.ImageField()
这是路由器,
router.register(r'user', UserViewSet),
router.register(r'user/profile', UserProfileViewSet, basename='UserProfile')
更新特定用户Profile的路径是什么,比如user_id 3。我是django新手。
这取决于您将在视图UserProfileViewSet
上设置的lookup_field
,如文档所示:
lookup_field
-应该用于执行单个模型实例的对象查找的模型字段
-
如果您想使用其他模型
User.user_id
的主键根据相关字段UserProfile.user
更新它,则:class UserProfileViewSet(viewsets.ModelViewSet): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer lookup_field = 'user' # Or "user_id"
URL路径为:
http://127.0.0.1:8000/my_app/user/profile/123/
其中
123
为用户的user_id
。 -
如果您想根据相关字段
UserProfile.user
更新它,但使用相关表上的另一个字段,例如User.username
(仅为了示例,假设它在您的User
模型中并且是唯一的)class UserProfileViewSet(viewsets.ModelViewSet): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer lookup_field = 'user__username'
URL路径为:
http://127.0.0.1:8000/my_app/user/profile/john_lennon/
其中
john_lennon
为用户的username
。
供您考虑。如果您希望id在User
和UserProfile
之间保持一致,而user_id
正好相当于profile_id
,您可以考虑将其作为UserProfile
的主键
class UserProfile(Base):
profile_id = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile', primary_key=True)
...
这样,你的lookup_field
就可以只是profile_id
,因为它相当于user_id
。