代码之家  ›  专栏  ›  技术社区  ›  Naroju

Django嵌套的序列化程序筛选器仅用于一个字段,而不是所有字段

  •  0
  • Naroju  · 技术社区  · 6 年前

    我有两个序列化程序如下。下面代码段的输出是Workers,并带有与所有字段相关联的票证计数器详细信息( ticket_counter , ticket_counter_name worker ). 但我只需要一个领域 售票处名称

    class WorkerSerializer(serializers.ModelSerializer):
    
        ticket_counter = WorkerToCounterSerializer(many=True, read_only=True)
    
        class Meta:
            model = User
            fields = (
                      'username',
                      'ticket_counter',
                      )
    
    class WorkerToCounterSerializer(serializers.ModelSerializer):
        ticket_counter = SerializerMethodField()
        ticket_counter_name = serializers.CharField(source='ticket_counter.ticket_counter_name')
    
        class Meta:
            model = WorkerToTicketCounter
            list_serializer_class = FilteredListSerializer
            fields = (
                'ticket_counter',
                'ticket_counter_name',
                'worker',
            )
    
        def get_ticket_counter(self, obj):
            return obj.ticket_counter.pk
    
    class FilteredListSerializer(ListSerializer):
        def to_representation(self, data):
            data = data.filter(worker_to_ticket_counter_is_deleted=False)[:1]
            return super(FilteredListSerializer, self).to_representation(data)
    

    上面的代码段输出了什么

    {
            "username": "xxxxxxxxxxx",
            "ticket_counter": [
                {
                    "ticket_counter": 7,
                    "ticket_counter_name": "Entrance Counter",
                    "worker": 4,
    
                }
            ]
     }
    

    但我想要的是

     {
            "username": "xxxxxxxxxxx",
            "ticket_counter": "Entrance Counter"
     }
    

    我只需要你的名字 . 就我而言,一个工人不能有两个售票处。显然,它只给出了一个 售票柜台 . 有可能吗?

    编辑:使用字符串 StringRelatedField

    {
        "username": "xxxxxxxxxxx",
        "ticket_counter": [
              "Entrance Counter",
              "xxxxxxxxxxxxxxxx",
              "xxxxxxxxxxxxxxxx",
              "xxxxxxxxxxxxxxxx"
        ]
    }
    

    编辑: WorkerToTicketCounter

    class WorkerToTicketCounter(models.Model):
        user = models.ForeignKey(User, on_delete=models.CASCADE)
        ticket_counter = models.ForeignKey(TicketCounter, related_name="workers")
        worker = models.ForeignKey(User, related_name='ticket_counter')
        worker_to_ticket_counter_is_deleted = models.BooleanField(default=False)
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   JPG    6 年前

    序列化方法字段 两者兼而有之 过滤 字符串表示

    class WorkerSerializer(serializers.ModelSerializer):
        ticket_counter = serializers.SerializerMethodField(read_only=True)
    
        def get_ticket_counter(self, user):
            qs = user.ticket_counter.filter(worker_to_ticket_counter_is_deleted=False)
            if qs.exists() and hasattr(qs.first().ticket_counter, 'ticket_counter_name'):
                return qs.first().ticket_counter.ticket_counter_name
            return None
    
        class Meta:
            model = User
            fields = ('username', 'ticket_counter',)
        2
  •  0
  •   neverwalkaloner    6 年前

    你可以用 StringRelatedField :

    class WorkerSerializer(serializers.ModelSerializer):
    
        ticket_counter = StringRelatedField(many=True, read_only=True)
    
        class Meta:
            model = User
            fields = (
                      'username',
                      'ticket_counter',
                      )
    

    字符串相关字段 __str__ WorkerToTicketCounter 型号:

    class WorkerToTicketCounter:
        ...
        def __str__(self):
            return self.ticket_counter.ticket_counter_name