以下是我的例子:
models.py:
class Example(models.Model):
title = models.CharField(...)
description = models.CharField(...)
class Foo(models.Model):
example = models.ManyToManyField(Example)
序列化器.py:
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
fields = '__all__'
depth = 1
views.py:
...
serialized_data = [FooSerializer(foo).data for foo in Foo.objects.all().get]
在输出中,我只收到Example
的ID,但是有什么方法可以获取标题和描述字段(m2mfield的详细信息)?据我了解, Foo.objects.all().get 根本不包含此数据,但也许我可以以某种方式获取并使用它?
如果需要,我还可以重建模型,但目前我使用 m2mf,因为需要包含与此模型数据相关的多个对象。
更新
models.py:
class Event(models.Model):
ts = models.BigIntegerField(editable=False)
class Foo(Event):
user = models.ForeignKey(User, ...)
example = *...(remains to be the same)*
foos = models.ForeignKey('self', **somemore** null=True)
序列化器.py:
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
fields = '__all__'
def to_representation(self, instance):
result = {'ts': instance.ts}
if isinstance(instance, Foo):
result['foo'] = FooSerializer(instance).data
return result
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username')
class FooSerializer(serializers.ModelSerializer):
# user = UserSerializer(read_only=True) # with this I have an error: Got AttributeError when attempting to get a value for field 'username' on #serializer 'UserSerializer'
class Meta:
model = Foo
fields = '__all__'
depth = 1
最佳答案
您可以使用depth
属性以实现所需的输出。
The default ModelSerializer uses primary keys for relationships, but you can also easily generate nested representations using the depth option.The depth option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
fields = '__all__'
<b>depth = 1</b>
除了答案之外,我还想更改您的 views.py
代码,因为它看起来非常糟糕:(。在 DRF Way 上这样做
serialized_data = FooSerializer(Foo.objects.all(), many=True).data<br>
示例 View
from rest_framework.viewsets import ModelViewSet
class FooViewset(ModelViewSet):
serializer_class = FooSerializer
queryset = Foo.objects.all()
UPDATE-1
<b>class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
exclude = ('password',) # add fields that are need to be excluded </b>
class FooSerializer(serializers.ModelSerializer):
<b>user = UserSerializer()</b>
class Meta:
model = Foo
fields = '__all__'
depth = 1
深度= 1
将序列化模型
中的所有字段,(与设置相同序列化器 Meta 类中的 >fields=='__all__'
)
UPDATE-2
class FooSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = Foo
fields = '__all__'
<b>depth = 1</b>
<b>def to_representation(self, instance):
real_data = super().to_representation(instance).copy()
# DO YOUR EXTRA CHECKS
child = UserSerializer(instance.child_foo).data
if child:
real_data.update({"child_data": child})
# After your checks, add it to "real_data"
return real_data</b>
我假设我有一个 Foo
模型
class Foo(models.Model):
example = models.ManyToManyField(Example)
user = models.ForeignKey(User)
child_foo = models.ForeignKey('self', null=True, blank=True)
关于python - ManyToManyField 序列化模型缺乏数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51315694/