简体   繁体   English

Django-模型和序列化程序类,最好的方法

[英]Django - model and serializer class, the best way to do

firstly let me explain the situation. 首先让我解释一下情况。 I have a model that basically have a title and a TextField that will save a json: 我有一个模型,基本上有一个标题和一个将保存json的TextField:

class Content(UUIDObject):
    title = models.CharField(_(u"Title"), max_length=300)
    custom_fields_json = models.TextField(_(u"Settings"))

To create this json, I must use a serializer class, from django rest framework. 要创建此json,我必须使用django rest框架中的序列化器类。 This class doesn't have a link to any model. 此类没有任何模型的链接。

class ConfigSerializer(serializers.Serializer):
    provider = serializers.CharField(write_only=True, required=True)
    provider_id = serializers.CharField(write_only=True, required=True)

The class above must be used to offer the user a form so he can fill title (from content model), provider and provider_id . 必须使用上面的类为用户提供表单,以便他可以填充title (来自内容模型), providerprovider_id The resulting json from the serializer class will be stored at custom_fields_json . 来自序列化程序类的结果json将存储在custom_fields_json The serializer class used in dynamic and I have the logic to return it working properly. 动态中使用的序列化器类,我具有使其正常工作的逻辑。

Currently I have a CreateView/UpdateView and adapting the code from this guide I can render the form with all the fields.. but then I just can't get the json from the serializer, etc... 目前,我有一个CreateView / UpdateView并改编了本指南中的代码,我可以使用所有字段来呈现表单。.但是然后我无法从序列化程序中获取json,等等。

I'm starting to think that this is the wrong way of doing it. 我开始认为这是错误的方法。 I would like to ask to guys with more experience if there is a better way of doing it, and what would it be. 我想问一个有更多经验的人,是否有更好的方法来做,这会是什么。

Thanks 谢谢

Use the ModelSerializer: 使用ModelSerializer:

class ConfigSerializer(serializers.ModelSerializer):
    class Meta:
        model = Content
        fields = ('title', 'custom_fields_json')

The serializer can give you a dict. 串行器可以给你一个字典。 Also read about ModelViewSets in django rest framework, they can significally minimize your code. 还要阅读有关Django rest框架中的ModelViewSets的信息,它们可以极大地减少您的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM