13👍
✅
Use SerializeMethodField:
class YourSerializer(serializers.ModelSerializer):
your_conditional_field = serializers.SerializerMethodField()
class Meta:
model = ToSerialize
def get_your_conditional_field(self, obj):
# do your conditional logic here
# and return appropriate result
return obj.content_type > obj.object_id
20👍
None of the answers actually answer the question.
The easy thing to do is to add all the fields by default and then remove it at initialisation of the serializer depending on your condition.
In the example below, we don’t give back the emails when listing users.
class UserSerializer():
fields = ('username', 'email')
class Meta:
model = User
def __init__(self, *args, **kwargs):
# Don't return emails when listing users
if kwargs['context']['view'].action == 'list':
del self.fields['email']
super().__init__(*args, **kwargs)
- [Django]-How do you detect a new instance of the model in Django's model.save()
- [Django]-Homepage login form Django
- [Django]-How to deal with "SubfieldBase has been deprecated. Use Field.from_db_value instead."
4👍
The recommended way is to create custom RelatedField. Check DRF docs about generic relationships for a nice example. In the OP case it would look like this:
class ABTypeRelatedField(serializers.RelatedField):
def to_representation(self, value):
"""
Serialize objects to a simple textual representation.
"""
if isinstance(value, AType):
return 'AType: ' + value.foo
elif isinstance(value, BType):
return 'BType: ' + value.bar
raise Exception('Unexpected type of content_object')
class ToSerializeSerializer(serializers.Serializer):
content_object = ABTypeRelatedField()
👤jozo
- [Django]-Iterating over related objects in Django: loop over query set or use one-liner select_related (or prefetch_related)
- [Django]-Django – SQL bulk get_or_create possible?
- [Django]-Django admin TabularInline – is there a good way of adding a custom html column?
Source:stackexchange.com