Django Serializer 仅返回父类对象的 JSON 并保留子对象相同?
我有这些模型:
class Projects(models.Model):
projectName =models.CharField(max_length = 100,unique=True,db_index=True)
projectManager = EmbeddedModelField('Users')
class Teams(models.Model):
teamType = models.CharField(max_length =100)
teamLeader = EmbeddedModelField('Users')
teamProject = EmbeddedModelField('Projects')
class Users(models.Model):
name = models.CharField(max_length = 100,unique=True)
designation = models.CharField(max_length =100 )
teams = ListField(EmbeddedModelField('Teams'))
我需要从我的视图中返回 JSON,以获取与用户和团队进一步相关的所有项目对象。我的views.py 有此代码
from django.core import serializers
data = serializers.serialize('json', Projects.objects.all())
此输出 JSON 仅适用于项目对象,并且不会为 User 对象返回 JSON,如下
[{"pk": "4eb3b7d0e814520db4000000", "model": "RESTAPI.projects", "fields": {"projectName": "HELLO", "projectManager": "Users object"}}]
所示我是否也将 User 对象转换为 JSON?
I have these models:
class Projects(models.Model):
projectName =models.CharField(max_length = 100,unique=True,db_index=True)
projectManager = EmbeddedModelField('Users')
class Teams(models.Model):
teamType = models.CharField(max_length =100)
teamLeader = EmbeddedModelField('Users')
teamProject = EmbeddedModelField('Projects')
class Users(models.Model):
name = models.CharField(max_length = 100,unique=True)
designation = models.CharField(max_length =100 )
teams = ListField(EmbeddedModelField('Teams'))
I need to return JSON from my view for all Projects objects which further has relations with Users and Teams.My views.py has this code
from django.core import serializers
data = serializers.serialize('json', Projects.objects.all())
This output JSON only for project object and doesnot return JSON for USer object like this
[{"pk": "4eb3b7d0e814520db4000000", "model": "RESTAPI.projects", "fields": {"projectName": "HELLO", "projectManager": "Users object"}}]
How do I convert the User object into JSON as well ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我前段时间遇到过这个问题,我创建了一个代码片段来帮助我解决:
所以你可以使用这样的东西:
免责声明:我为自己的目的编写了脚本;它可能并不完美,可能需要进一步修改以满足您自己的需求。
I've hit this problem some time ago, and I created a snippet to help me out:
So you could use something like this:
disclaimer: I made the script for my own purposes; it may not be perfect, it may require further modifications to fit your own needs.
我遇到了同样的问题,这是我的情况:
Tl;dr:
您需要为您使用的每个嵌入式模型制作一个序列化器,并将其设置到“父亲”序列化器中。这样您的输出将序列化您的嵌入式模型。
models.py
serializers.py
views.py
JSON 输出
I had the same problem, here is my case:
Tl;dr:
You need to make a serializer for each embedded model you use, and set it into the "father" serializer. That way your output will serialize your embedded model.
models.py
serializers.py
views.py
JSON output