更新链接模型上的数据



这是我的用户模型,

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-应该用于执行单个模型实例的对象查找的模型字段

  1. 如果您想使用其他模型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

  2. 如果您想根据相关字段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在UserUserProfile之间保持一致,而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

最新更新