使用 ManyToManyField 的序列化模型缺少数据
Lack of data with serialization model with ManyToManyField
以下是我的示例:
models.py:
class Example(models.Model):
title = models.CharField(...)
description = models.CharField(...)
class Foo(models.Model):
example = models.ManyToManyField(Example)
serializers.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,因为需要包含与此模型数据相关的多个 objects。
更新
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)
serializers.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
在您的序列化程序中添加深度 = 1。示例,其中 'users' 是相关字段:
FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
fields = ('id', 'account_name', 'users', 'created')
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 as
serialized_data = FooSerializer(Foo.objects.all(), many=True).data<br>
示例视图
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
depth = 1
将在 model
中序列化 all 字段,(与设置 fields=='__all__'
在序列化器的 Meta class 中)
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)
以下是我的示例:
models.py:
class Example(models.Model):
title = models.CharField(...)
description = models.CharField(...)
class Foo(models.Model):
example = models.ManyToManyField(Example)
serializers.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,因为需要包含与此模型数据相关的多个 objects。
更新
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)
serializers.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
在您的序列化程序中添加深度 = 1。示例,其中 'users' 是相关字段:
FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
fields = ('id', 'account_name', 'users', 'created')
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 as
serialized_data = FooSerializer(Foo.objects.all(), many=True).data<br>
示例视图
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
depth = 1
将在 model
中序列化 all 字段,(与设置 fields=='__all__'
在序列化器的 Meta class 中)
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)