Django Rest Framework, how to save model with associated field based on identifier

I am a little new to DRF. I have a recording model that looks like this:

class Records(models.Model): owner = models.ForeignKey(User, null=True) activity = models.ForeignKey(Activity, null=True) time_start = models.DateTimeField(null=True) time_end = models.DateTimeField(null=True) ... 

RecordSerializer is as follows:

 class RecordSerializer(serializers.ModelSerializer): now = datetime.today() owner = serializers.Field(source='owner.username') time_start = serializers.DateTimeField(source='now') class Meta: model = Records fields = ("owner", "activity", "time_start") 

And this is the view:

 class StartApiView(generics.CreateAPIView): model = Records serializer_class = RecordSerializer def pre_save(self, obj): obj.owner = self.request.user 

The POST request is sent from Backbone and includes a field with an activity identifier, for example, "{activity: 12}". What if I want the view to keep a record and set activity for Activity with id 12?

+6
source share
2 answers

The Django REST Framework provides PrimaryKeyRelatedField for this use case.

 class RecordSerializer(serializers.ModelSerializer): activity = serializers.PrimaryKeyRelatedField() owner = serializers.CharField(read_only=True, source='owner.username') time_start = serializers.DateTimeField(source='now') class Meta: model = Records fields = ("owner", "activity", "time_start") 

This will produce a result similar to what you are looking for, and will take the action id when you want to update it.

+2
source

The accepted answer was right for DRF v2.x , but is no longer intended for newer versions (3.x) , as this raises this AssertionError :

AssertionError: The relational field must contain the queryset argument or set read_only=True .

For newer versions, just add the queryset argument to it:

 class RecordSerializer(serializers.ModelSerializer): activity = serializers.PrimaryKeyRelatedField(queryset=Activity.objects.all()) // [...] 
+17
source

Source: https://habr.com/ru/post/978423/


All Articles