ForiegnKey field serializer in Django Rest framewo

2019-08-21 12:39发布

问题:

Before posting this question I've read few questions on SOF. but they are from 2012 and very confusing as well. for e.g Django Rest Framework - Get related model field in serializer

my question is very straight forward

models.py

class User(models.Model):
    username = models.CharField(max_length=100,unique=True)
    password = models.CharField(max_length=100,null=False,blank=False)

class Car(models.Model):
    user = models.ForeignKey(User)
    car_name = models.CharField(max_length=100,null=True,blank=True)

serializers.py

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username','password' )

class CarSerializer(serializers.ModelSerializer):
    #user = ?? what should I write or is there any better approach for serializing Car objects
    class Meta:
        model = Car
        fields = ('user','car_name')

views.py

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class CarViewSet(viewsets.ModelViewSet):
    queryset = Car.objects.all()
    serializer_class = CarSerializer

Please suggest all possible approaches.

1 more query. which one is better ModelSerializer or HyperlinkModelSerializer. as I saw different different answers containing these two.

回答1:

You just need to do:

class CarSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    class Meta:
        model = Car
        fields = ('user','car_name')

that is all.

Also, you should take a look to the kindnesses of serializers.Field and serializers.SerializerMethodField, you can play with them and customize your response data as much as you wish.

As to the question around HyperlinkedModelSerializer-ModelSerializer, very clear here:

The HyperlinkedModelSerializer has the following differences from ModelSerializer:

  • It does not include the pk field by default.
  • It includes a url field, using HyperlinkedIdentityField.
  • Relationships use HyperlinkedRelatedField, instead of PrimaryKeyRelatedField.

Hope that helps.