Django Rest Framework how to save a model with Related Field based on ID
django, django-models, django-rest-framework
Solution
Django REST Framework provides a `PrimaryKeyRelatedField` for exactly 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 output similar to what you are looking for, and it will accept the `id` of the activity when you want to update it.
Problem
I'm kind of new to DRF. I have Record 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) ... ``` The RecordSerializer is this one: ``` 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 it includes a field with the activity id, for example "{activity:12}". What should I do if I want the view to save the Record and set the activity to the Activity with the id of 12?