I've of course reviewed the docs, but was wondering if anyone could more succinctly explain the difference in use case and application between these fields. Why would one use one field over the other? Would there be a difference between these fields for a OneToOne relationship?
PrimaryKeyRelatedField. PrimaryKeyRelatedField may be used to represent the target of the relationship using its primary key. For example, the following serializer: class AlbumSerializer(serializers. ModelSerializer): tracks = serializers.
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.
As stated in the documentation, you will need to write your own create() and update() methods in your serializer to support writable nested data. You will also need to explicitly add the status field instead of using the depth argument otherwise I believe it won't be automatically added to validated_data .
Django is the web development framework in python whereas the Django Rest Framework is the library used in Django to build Rest APIs. Django Rest Framework is especially designed to make the CRUD operations easier to design in Django. Django Rest Framework makes it easy to use your Django Server as an REST API.
You would use a HyperlinkedIdentityField
to link to the object currently being serialized and a HyperlinkedRelatedField
to link to objects related to the one being serialized.
So for a one-to-one relationship, foreign key relationship, many-to-many relationship and basically anything else involving relationships (in Django models), you want to use a HyperlinkedRelatedField
. The only time where a HyperlinkedRelatedField
is used is for the url
field which you can include on your serializer to point to the current object.
In Django REST framework 3.0.0, there are only two differences between a HyperlinkedRelatedField
and HyperlinkedIdentityField
.
source
is automatically set to *
(the current object)read_only=True
, so it can't be changedWhich means that setting a HyperlinkedRelatedField
with those properties is exactly the same as having a HyperlinkedIdentityField
.
In older versions of Django REST framework (before 3.0.0), the HyperlinkedIdentityField
used to be a dedicated field for resolving the url for the current object. It accepted a slightly different set of parameters and was not a subclass of HyperlinkedRelatedField
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With