实现条件相对表django-rest-framework

时间:2017-03-30 07:39:21

标签: django-rest-framework

我有两个模型

class Parent(models.Model):
    name = models.CharField(max_length=50)


class Child(models.Model):
    parent = models.ForeignKey(Parent,related_name='child')
    child_name = models.CharField(max_length=80)
    type = models.BooleanField()

我在serializer.py上实现了这个逻辑

class ChildSerializer(serializers.ModelSerializer):
    class Meta:
        model = Login
        fields = ('id', 'parent', 'child_name','type')


class ParentSerializer(serializers.ModelSerializer):
    child = ChildSerializer(many=True, read_only=True)
    class Meta:
        model = Catcher
        fields = ('id','name', 'child')

我在Parent上查询并获取子表中的所有数据,但我希望子表上的实现条件只能获得type = 1

a = Parent.objects.get(pk = 1)
serializer = ParentSerializer(a, many=True)

它给了我这个json

{
    "id": 51,
    "name": "Rijo",
    "child": [
        {
          "id": 98,
          "name": "Child 1",
          "type" : 1
        },
        {
          "id": 10,
          "name": "Child 2",
          "type" : 0
        }

    ]
}

但我只想要1型孩子,如何在子查询上实现条件

2 个答案:

答案 0 :(得分:3)

  1. 在父模型中实现方法或属性:

    class Parent(models.Model):
        name = models.CharField(max_length=50)
    
        def first_type_children(self):
            return self.child.filter(type=1)
    
  2. 在序列化程序字段中将其用作source

    class ParentSerializer(serializers.ModelSerializer):
        child = ChildSerializer(source='first_type_children', many=True, read_only=True)
    

答案 1 :(得分:0)

替代方法:

class ParentSerializer(serializers.ModelSerializer):
    child = serializers.SerializerMethodField('first_type_children')

    def first_type_children(self,obj):
        child_objects = Child.objects.filter(type=1,parent=obj)
        # child_objects = self.child_set.filter(type=1) 
        serializers = ChildSerializer(child_objects,many=True)
        return serializers.data

否则,您可以定义:

class ParentSerializer(serializers.ModelSerializer):
   child = serializers.SerializerMethodField()

   def get_child(self,obj):
        child_objects = self.child_set.filter(type=1) 
        serializers = ChildSerializer(child_objects,many=True)
        return serializers.data

但是我建议使用@zymud方法,使其成为模型中的属性。因为它会减少您的代码。

例如:如果您在多个地方使用QuerySet /过滤器,您可以在模型上使用getter函数,然后甚至删除Serializer / Field的'source'kwarg。

  1. models.py

    class Parent(models.Model):
        name = models.CharField(max_length=50)
    
        def first_type_children(self):
            return self.child.filter(type=1)
    
  2. 序列化程序中的
  3. class ParentSerializer(serializers.ModelSerializer):
        first_type_children = ChildSerializer(many=True, read_only=True)
    
  4. 希望这有助于某人!