这是我的例子:
models.py:
res.render('admin', {msg: err, title: <your title here>});
serializers.py:
class Example(models.Model):
title = models.CharField(...)
description = models.CharField(...)
class Foo(models.Model):
example = models.ManyToManyField(Example)
views.py:
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
fields = '__all__'
depth = 1
在输出中,我仅收到...
serialized_data = [FooSerializer(foo).data for foo in Foo.objects.all().get]
的ID,但是还有什么方法可以获取标题和描述字段(m2mfield的详细信息)?据我了解,Example
根本不包含这些数据,但是也许我能以某种方式获取并使用它?
如果需要,我也可以重建模型,但是由于需要包含多个与此模型数据相关的对象,因此我目前使用m2mf。
更新
models.py :
Foo.objects.all().get
serializers.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)
答案 0 :(得分:2)
您可以使用depth
属性来获得所需的输出。
默认的 ModelSerializer 使用主键建立关系,但是 您还可以使用 depth 轻松生成嵌套表示 深度选项应设置为一个整数值 表示应该遍历的关系深度 恢复为平面表示形式。
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
fields = '__all__'
depth = 1
除了答案之外,我还想更改您的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
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
exclude = ('password',) # add fields that are need to be excluded
class FooSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = Foo
fields = '__all__'
depth = 1
depth = 1
将对model
中的所有字段进行序列化,(与在序列化器的Meta类中设置fields=='__all__'
相同) )
UPDATE-2
class FooSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = Foo
fields = '__all__'
depth = 1
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
我以为我有一个Foo
模型为
class Foo(models.Model):
example = models.ManyToManyField(Example)
user = models.ForeignKey(User)
child_foo = models.ForeignKey('self', null=True, blank=True)
答案 1 :(得分:1)
在序列化器中添加depth =1。示例中'users'是相关字段:
FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
fields = ('id', 'account_name', 'users', 'created')
depth = 1