Django rest框架根据当前的userId / token获取数据

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

在我的模型中,我有一个家庭表,用户可以输入他们的家庭详细信息并存储他们的信息。但是如何根据当前的userId获取/查询所有家庭成员?

例如:userId = 1添加了2个家庭成员,母亲和父亲。如何根据当前用户的userId查询获得这2个家庭成员?

这是我的代码:

楷模

class MyUser(AbstractUser):
    userId = models.AutoField(primary_key=True)
    gender = models.CharField(max_length=6, blank=True, null=True)
    nric = models.CharField(max_length=40, blank=True, null=True)
    birthday = models.DateField(blank=True, null=True)
    birthTime = models.TimeField(blank=True, null=True)

class Family(models.Model):
    userId = models.ForeignKey(MyUser)
    relationship = models.CharField(max_length=100)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    gender = models.CharField(max_length=6, blank=True, null=True)

串行

class MyUserSerializer(serializers.ModelSerializer):
    valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p']
    birthTime = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats, allow_null=True, required=False)

    class Meta:
        model = MyUser
        fields = ['userId', 'username', 'email', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'birthTime']
        read_only_fields = ('userId',)
        extra_kwargs = {"password": {"write_only": True}}

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            if attr == 'password':
                instance.set_password(value)
            else:
                setattr(instance, attr, value)
        instance.save()
        return instance


class FamilySerializer(serializers.ModelSerializer):

    class Meta:
        model = Family
        fields = ('id', 'userId', 'first_name', 'last_name', 'gender', 'relationship')

意见

class MyUserViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = MyUser.objects.all()
    serializer_class = MyUserSerializer
    filter_backends = (filters.SearchFilter,)
    search_fields = ('=userId', 'username', 'email', 'first_name', 'last_name')


class FamilyViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = Family.objects.all()
    serializer_class = FamilySerializer


def get_object(self, *args, **kwargs):
    return self.request.user

def perform_update(self, serializer):
    super(CurrentFamilyView, self).perform_update(serializer)
    user = serializer.instance
    if settings.SEND_ACTIVATION_EMAIL and not user.is_active:
        context = {'user': user}
        to = [MyUser(user)]
        email.ActivationEmail(self.request, context).send(to)

任何人都可以帮助我获得当前用户的家人

django django-rest-framework
2个回答
2
投票

你可以试试这个:

class Family(models.Model):
    userId = models.ForeignKey(MyUser, related_name='user_family')
    relationship = models.CharField(max_length=100)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    gender = models.CharField(max_length=6, blank=True, null=True)

serialize认识.朋友

class FamilySerializer(serializers.ModelSerializer):

    class Meta:
        model = Family
        fields = ('id', 'first_name', 'last_name', 'gender', 'relationship')


class MyUserSerializer(serializers.ModelSerializer):

    valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p']
    birthTime = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats, allow_null=True, required=False)
    my_family = FamilySerializer(many=True, source='user_family')

    class Meta:
        model = MyUser
        fields = ('userId', 'username', 'email', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'birthTime', 'my_family')
        read_only_fields = ('userId',)
        extra_kwargs = {"password": {"write_only": True}}

MyUserSerializer现在将展示userid相关的家庭成员。如果您想获得当前用户家庭成员,则需要覆盖get_queryset方法。

你的views.py:

class MyUserViewSet(viewsets.ModelViewSet):

    serializer_class = MyUserSerializer
    get_queryset(self):
        return  MyUser.objects.get(id=self.request.user.id)

现在视图将返回当前用户系列成员。

更新

  1. related_name模型中添加了Family
  2. source添加了MyUserSerializer

1
投票

假设我们有一个id = 1的用户

usr = MyUser.objects.get(id=1)
usr_famly = usr.family_set.values()

usr_famly将拥有与user with id=1相关的所有家庭数据

© www.soinside.com 2019 - 2024. All rights reserved.