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?
Django REST Framework is used to create web APIs very easily and efficiently. This is a wrapper around over the Django Framework. There are three stages before creating an API through REST framework, Converting a Model’s data to JSON/XML format (Serialization), Rendering this data to the view, Creating a URL for mapping to the viewset.
In this post, you will learn how to Pass Extra Data to a Django REST Framework Serializer and Save it to the Database. In a standard Django form, a code snippet of the procedure would look like this: form = VoterForm (request.POST) if form.is_valid (): voter = form.save (commit=False) voter.user = request.user voter.save ()
In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this isn’t usually permitted for model fields.
Instead, when it is used as a base class for other models, its fields will be added to those of the child class. The Student model will have three fields: name, age and home_group. The CommonInfo model cannot be used as a normal Django model, since it is an abstract base class.
The accepted answer was true for DRF v2.x but is no longer for newer (3.x) versions, as it would raise this AssertionError
:
AssertionError: Relational field must provide a
queryset
argument, or setread_only=True
.
For newer versions, just add the queryset
argument to it:
class RecordSerializer(serializers.ModelSerializer):
activity = serializers.PrimaryKeyRelatedField(queryset=Activity.objects.all())
// [...]
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