I want to serialize a model, but want to include an additional field that requires doing some database lookups on the model instance to be serialized:
class FooSerializer(serializers.ModelSerializer):
my_field = ... # result of some database queries on the input Foo object
class Meta:
model = Foo
fields = ('id', 'name', 'myfield')
What is the right way to do this? I see that you can pass in extra "context" to the serializer, is the right answer to pass in the additional field in a context dictionary? With that approach, the logic of getting the field I need would not be self-contained with the serializer definition, which is ideal since every serialized instance will need my_field
. Elsewhere in the DRF serializers documentation it says "extra fields can correspond to any property or callable on the model". Is extra fields what I'm talking about? Should I define a function in Foo
's model definition that returns my_field
value, and in the serializer I hook up my_field to that callable? What does that look like?
Thanks in advance, happy to clarify the question if necessary.
With the last version of Django Rest Framework, you need to create a method in your model with the name of the field you want to add. No need for
@property
andsource='field'
raise an error.You can change your model method to property and use it in serializer with this approach.
Edit: With recent versions of rest framework (I tried 3.3.3), you don't need to change to property. Model method will just work fine.
In model.py
**
**
**
if you want read and write on your extra field, you can use a new custom serializer, that extends serializers.Serializer, and use it like this
i use this in related nested fields with some custom logic
My response to a similar question (here) might be useful.
If you have a Model Method defined in the following way:
You can add the result of calling said method to your serializer like so:
p.s. Since the custom field isn't really a field in your model, you'll usually want to make it read-only, like so:
As Chemical Programer said in this comment, in latest DRF you can just do it like this:
DRF docs source