7👍
✅
if you want to be able to specify the for_key
then you can’t use @Withnail’s answer because the for_key
there is read_only.
You should use a PrimaryKeyRelatedField.
class BSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(format='hex')
for_key = serializers.PrimaryKeyRelatedField(queryset=A.objects.all())
class Meta:
model = B
fields = ('id', 'desc', 'for_key')
2👍
When you serialize across a relationship in DRF, you just need to call the serializer in the second model.
class ASerializer(serializers.ModelSerializer):
id = serializers.UUIDField(format='hex')
class Meta:
model = A
fields = ('id', 'desc')
class BSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(format='hex')
for_key = ASerializer(many=True, read_only=True)
class Meta:
model = B
fields = ('id', 'desc', 'for_key')
- [Django]-Django – use same column for two foreign keys
- [Django]-Extract values from Django <QuerySet> in Python 3
2👍
What you are looking for is :
class BSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(format='hex')
for_key = serializers.UUIDField(format='hex', source='for_key.id')
class Meta:
model = B
fields = ('id', 'desc', 'for_key')
- [Django]-Segmentation fault (core dumped) with django-storages
- [Django]-Django-allauth: custom signup form for socialaccount
- [Django]-How to convert Foreign Key Field into Many To Many Field without disturbing existing data in the database?
Source:stackexchange.com