zoukankan      html  css  js  c++  java
  • python – Django-Rest-Framework – 如何将不相关模型中的查询集序列化为嵌套序列化程序

    我正在尝试根据父模型的某些条件(而不是外键)将嵌套的序列化程序添加到现有的序列化程序中.用例是返回一个’Research’对象,其中包含一系列’ResearchTemplate’对象,这些对象通过在postgres ArrayField上过滤来识别.

    楷模

    class Research(TimeStampedModel):
        category = models.CharField(max_length=100, choices=RESEARCH_TEMPLATE_CATEGORIES, default='quote')
        body = models.CharField(max_length=1000, blank=True, default='') #The body of text comprising the nugget
        additionaldata = JSONField(null=True) # all the varying values to be merged into a wrapper
    
        def __str__(self):
            return self.body
    
        class Meta:
            ordering = ('created',)
    
    class ResearchTemplate(TimeStampedModel):
        template = models.TextField(blank=True, default='')
        category = models.CharField(max_length=100, choices=RESEARCH_TEMPLATE_CATEGORIES, default='quote')
        mergefields = ArrayField(models.CharField(max_length=200), blank=True)
    
        def save(self, *args, **kwargs):
            merges = re.findall("{{(.*?)}}", self.template) #get all the template names from within the mustaches
            self.mergefields = list(set(merges)) #TODO: Make Unique
            super(TimeStampedModel, self).save(*args, **kwargs)
    
        def __str__(self):
            return self.wrapper
    
        class Meta:
            ordering = ('created',)
    
    

    串行器

    class ResearchSerializer(serializers.ModelSerializer):
            templates = ResearchTemplateSerializer(many=True)
    
            class Meta:
                model = Research
                fields = ('id', 'created', 'speaker', 'body', 'templates')
    
    class ResearchTemplateSerializer(serializers.RelatedField):
            def get_queryset(self, values):
                return ResearchTemplate.objects.filter(mergefields__contained_by=['django']) #This must an array of keys from the Research object's JSON field
    
            class Meta:
                model = ResearchTemplate
                fields = ('id', 'template')
    
    

    当有外键映射它时,我已经能够嵌套序列化程序,但无法使用自定义查询集.也许我没有正确地思考这个问题,我在研究模型上需要某种形式的“关系”字段.

    如何嵌套从过滤器返回的所有行的序列化列表,其中包含从父模型指定的值?

     
    您可以使用DRF的SerializerMethodField http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield.

    将ResearchTemplateSerializer定义为普通的ModelSerializer,而不是RelatedField.

    然后用这个替换你的ResearchSerializer:

    class ResearchSerializer(serializers.ModelSerializer):
        templates = serializers.SerializerMethodField()
    
        class Meta:
            model = Research
            fields = ('id', 'created', 'speaker', 'body', 'templates')
    
        def get_templates(self, obj):
            values = obj.get_values() # whatever your filter values are. obj is the Research instance
            templates = ResearchTemplate.objects.filter(mergefields__contained_by=values) # Or whatever queryset filter
            return ResearchTemplateSerializer(templates, many=True).data
    转载:http://www.voidcn.com/article/p-hbxnetdf-bvo.html

  • 相关阅读:
    Rust started
    修改cargo镜像源
    如何激发团队潜能?
    JVM 09.5 运行时数据区 堆 堆时对象分配的唯一选择吗 逃逸分析
    JVM 09.5 运行时数据区 堆 相关参数设置总结
    JVM 09.4 运行时数据区 堆 线程独占区域 TLAB
    JVM 09.3 运行时数据区 堆 调优/垃圾回收/小结
    JVM 09.2 运行时数据区 堆 年轻带/老年代/对象分配过程
    JVM 09.1 运行时数据区 堆 核心概述
    JVM 08 运行时数据区 本地方法栈
  • 原文地址:https://www.cnblogs.com/catgatp/p/12976691.html
Copyright © 2011-2022 走看看