HyperlinkedModelSerializer可写相关领域

时间:2018-07-02 14:00:15

标签: django django-rest-framework

型号:

class User(AbstractUser):
    ROLE_CHOICES = (
         ('R', 'rider'),
         ('D', 'driver'),
    )
    role = models.CharField(max_length=1, choices=ROLE_CHOICES)
    phone_number = models.CharField(max_length=10)
    cab = models.OneToOneField('Cab', on_delete=models.CASCADE, blank=True, null=True)

class Cab(models.Model):
    color = models.CharField(max_length=20)
    rn = models.CharField(max_length=20)
    available = models.BooleanField(default=True)
    model = models.CharField(max_length=50)

驱动程序序列化器:

class DriverSerializer(serializers.HyperlinkedModelSerializer):
    cab = serializers.HyperlinkedIdentityField(view_name='cab_detail')
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'phone_number', 'cab', 'password')
        extra_kwargs = {
            'password': {'write_only': True},
            'cab': {'required':True}
        }
        #depth = 1
    def create(self, validated_data):
        password = validated_data.pop('password')
        instance = User(**validated_data)
        if password is not None:
           instance.set_password(password)
           instance.save()
        return instance

driver_list视图

@api_view(['GET', 'POST'])
def driver_list(request):
    if request.method == 'GET':
        riders = User.objects.filter(role='D')
        serializer_context = {
            'request': request,
        }
        serializer = DriverSerializer(riders, context = serializer_context, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        #context = {'role':'D'}
        #serializer = DriverSerializer(data=request.data, context=context)
        serializer_context = {
            'request': request,
        }
        serializer = DriverSerializer(data=request.data, context = serializer_context)
        if serializer.is_valid(raise_exception=True):
            serializer.save(role='D')
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

这将在GET驱动程序上提供以下输出/

cab字段指向具有与用户对象ID相同ID的Cab对象

[
    {
        "id": 2,
        "username": "aditi",
        "email": "aditi@gmail.com",
        "phone_number": "8130022156",
        "cab": "http://127.0.0.1:8000/api/cabs/2"
    },
    {
        "id": 7,
        "username": "test3",
        "email": "himanshu@gmail.com",
        "phone_number": "9976544776",
        "cab": "http://127.0.0.1:8000/api/cabs/7"
    },

在创建用户对象时,我希望cab字段指向在“ cab”中传递的参数。如何实现?

1 个答案:

答案 0 :(得分:0)

您应该改用HyperlinkedRelatedFieldHyperlinkedIdentityField用于当前对象,而不用于相关对象:

class DriverSerializer(serializers.HyperlinkedModelSerializer):
    cab = serializers.HyperlinkedRelatedField(view_name='cab_detail', read_only=False)