Django序列化相关对象

时间:2018-04-09 22:39:34

标签: django python-3.x

我有以下位置和用户模型。

class Location(models.Model):
    country = models.CharField(max_length=255)
    city = models.CharField(max_length=255, unique=True)
    latitude = models.CharField(max_length=255)
    longitude = models.CharField(max_length=255)

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True, max_length=255)
    mobile = PhoneNumberField(null=True)
    username = models.CharField(null=True, unique=True, max_length=255)
    full_name = models.CharField(max_length=255, blank=True, null=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)
    is_mobile_verified = models.BooleanField(default=False)
    location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True)

这些是各自的序列化程序。

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    id = serializers.IntegerField(read_only=True)

    class Meta:
        model = models.User
        fields = (
            'id', 'email', 'mobile', 'username', 'full_name', 'password', 'is_active', 'is_mobile_verified',
        )



class LocationSerializer(serializers.ModelSerializer):
        id = serializers.IntegerField(read_only=True)

        class Meta:
            model = models.Location
            fields = ('id', 'country', 'city', 'longitude', 'latitude')

现在我正在序列化并输出这样的数据。

return Response(UserSerializer(user).data, status=status.HTTP_200_OK)

我的问题是如何使用两个序列化器将用户数据与他的位置一起返回?

1 个答案:

答案 0 :(得分:1)

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    id = serializers.IntegerField(read_only=True)
    location = LocationSerializer(read_only=True)

    class Meta:
        model = models.User
        fields = (
            'id', 'email', 'mobile', 'username', 'full_name', 'password', 'is_active', 'is_mobile_verified', 'location'
        )



class LocationSerializer(serializers.ModelSerializer):
        id = serializers.IntegerField(read_only=True)

        class Meta:
            model = models.Location
            fields = ('id', 'country', 'city', 'longitude', 'latitude')