Django Serializer 仅返回父类对象的 JSON 并保留子对象相同?

发布于 2024-12-13 13:40:52 字数 990 浏览 1 评论 0原文

我有这些模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小情绪 2024-12-20 13:40:52

我前段时间遇到过这个问题,我创建了一个代码片段来帮助我解决

def get_values(instance, go_into={}, exclude=(), extra=()):
    """
    Transforms a django model instance into an object that can be used for
    serialization. Also transforms datetimes into timestamps.

    @param instance(django.db.models.Model) - the model in question
    @param go_into - relations with other models that need expanding
    @param exclude - fields that will be ignored
    @param extra - additional functions/properties which are not fields

    Usage:
    get_values(MyModel.objects.get(pk=187),
               {'user': {'go_into': ('clan',),
                         'exclude': ('crest_blob',),
                         'extra': ('get_crest_path',)}},
               ('image'))

    """

所以你可以使用这样的东西:

simplejson.dumps(get_values(Projects.objects.all(),
    go_into={'projectManager': {'go_into': 'teams'}}))

免责声明:我为自己的目的编写了脚本;它可能并不完美,可能需要进一步修改以满足您自己的需求。

I've hit this problem some time ago, and I created a snippet to help me out:

def get_values(instance, go_into={}, exclude=(), extra=()):
    """
    Transforms a django model instance into an object that can be used for
    serialization. Also transforms datetimes into timestamps.

    @param instance(django.db.models.Model) - the model in question
    @param go_into - relations with other models that need expanding
    @param exclude - fields that will be ignored
    @param extra - additional functions/properties which are not fields

    Usage:
    get_values(MyModel.objects.get(pk=187),
               {'user': {'go_into': ('clan',),
                         'exclude': ('crest_blob',),
                         'extra': ('get_crest_path',)}},
               ('image'))

    """

So you could use something like this:

simplejson.dumps(get_values(Projects.objects.all(),
    go_into={'projectManager': {'go_into': 'teams'}}))

disclaimer: I made the script for my own purposes; it may not be perfect, it may require further modifications to fit your own needs.

请恋爱 2024-12-20 13:40:52

我遇到了同样的问题,这是我的情况:

Tl;dr:
您需要为您使用的每个嵌入式模型制作一个序列化器,并将其设置到“父亲”序列化器中。这样您的输出将序列化您的嵌入式模型。

models.py

class Log(models.Model):
    status    = models.CharField(max_length=10, default='Sending')
    requested = models.DateTimeField(default=timezone.now)
    sent      = models.DateTimeField(null=True, default=None)
    log       = ListField(EmbeddedModelField('Log_Event'))

class Log_Message(models.Model):
    channel = models.ForeignKey(Channel)
    to      = models.CharField()
    message = models.CharField()

class Log_Event(models.Model):
    type    = models.CharField()
    message = models.CharField()
    date    = models.DateTimeField(default=timezone.now)

serializers.py

from rest_framework import serializers
from models         import Log, Log_Event, Log_Message

class LogMessageSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model  = Log_Message
        fields = ('channel', 'to', 'message')

class LogEventSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model  = Log_Event
        fields = ('type', 'message', 'date')


class LogSerializer(serializers.HyperlinkedModelSerializer):
    message = LogMessageSerializer()
    log     = LogEventSerializer()

    class Meta:
        model  = Log
        fields = ('status', 'requested', 'sent', 'log')

views.py

from models         import Log
from rest_framework import viewsets, filters
from serializers    import LogSerializer

class LogViewSet(viewsets.ModelViewSet):
    queryset         = Log.objects.all()
    serializer_class = LogSerializer
    filter_fields    = ('system', 'message', 'status', 'requested', 'sent', 'log')

JSON 输出

{
    "status": "Sent", 
    "requested": "2014-07-25T18:06:00.653", 
    "sent": "2014-07-25T18:06:03.707", 
    "log": [
        {
            "type": "starting...", 
            "message": "Trying to send...", 
            "date": "2014-07-25T18:06:00.659"
        }, 
        {
            "type": "success", 
            "message": "Mail SENT!", 
            "date": "2014-07-25T18:06:03.707"
        }
    ]
}

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

class Log(models.Model):
    status    = models.CharField(max_length=10, default='Sending')
    requested = models.DateTimeField(default=timezone.now)
    sent      = models.DateTimeField(null=True, default=None)
    log       = ListField(EmbeddedModelField('Log_Event'))

class Log_Message(models.Model):
    channel = models.ForeignKey(Channel)
    to      = models.CharField()
    message = models.CharField()

class Log_Event(models.Model):
    type    = models.CharField()
    message = models.CharField()
    date    = models.DateTimeField(default=timezone.now)

serializers.py

from rest_framework import serializers
from models         import Log, Log_Event, Log_Message

class LogMessageSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model  = Log_Message
        fields = ('channel', 'to', 'message')

class LogEventSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model  = Log_Event
        fields = ('type', 'message', 'date')


class LogSerializer(serializers.HyperlinkedModelSerializer):
    message = LogMessageSerializer()
    log     = LogEventSerializer()

    class Meta:
        model  = Log
        fields = ('status', 'requested', 'sent', 'log')

views.py

from models         import Log
from rest_framework import viewsets, filters
from serializers    import LogSerializer

class LogViewSet(viewsets.ModelViewSet):
    queryset         = Log.objects.all()
    serializer_class = LogSerializer
    filter_fields    = ('system', 'message', 'status', 'requested', 'sent', 'log')

JSON output

{
    "status": "Sent", 
    "requested": "2014-07-25T18:06:00.653", 
    "sent": "2014-07-25T18:06:03.707", 
    "log": [
        {
            "type": "starting...", 
            "message": "Trying to send...", 
            "date": "2014-07-25T18:06:00.659"
        }, 
        {
            "type": "success", 
            "message": "Mail SENT!", 
            "date": "2014-07-25T18:06:03.707"
        }
    ]
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文