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.
You just need to do:
that is all.
Also, you should take a look to the kindnesses of
serializers.Field
andserializers.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 fromModelSerializer
:HyperlinkedIdentityField
.HyperlinkedRelatedField
, instead ofPrimaryKeyRelatedField
.Hope that helps.