如何仅在Viewset Django中选择指定字段 [英] How to select specify field only in Viewset Django

查看:55
本文介绍了如何仅在Viewset Django中选择指定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想从Django ViewSet中选择唯一字段和某些字段.

I would like to select the distinct field and some field only from Django ViewSet.

我的方法

@action(methods=['get'], detail=False)
    def shiftsum(self, request):        
        query = (
                    Shift.objects.values('shiftid', 'dayname')
                        .annotate(shiftdesc=Max('shiftdesc'))
                        .annotate(ct=Count('*'))  # get count of rows in group
                        .order_by('shiftid', 'dayname')
                        .distinct()
                )
        serializer = self.get_serializer_class()(query,many=True)
        return Response(serializer.data)

我的模特

class Shift(models.Model):
    shiftid = models.CharField(max_length=15)
    shiftdesc = models.CharField(blank = False, null= False, max_length=20)
    dayname = models.CharField(blank = False, null= False, max_length=20)
    dayno = models.IntegerField(blank = False, null= False)
    offin_f = models.IntegerField(blank = False, null= False)
    .
    .
    .

我的序列化器

class ShiftSerializer(serializers.ModelSerializer):
    class Meta:        
        model=Shift
        fields = "__all__"

    def create(self,validated_data):      
        validated_data['Created_Usr']="Admin"             
        validated_data['Created_DT']=datetime.datetime.now()      
        validated_data['LastModified_Usr']=''            
        validated_data['LastModified_DT']=None            
        return Shift.objects.create(**validated_data)

    def update(self,instance,validated_data):       
        instance.shiftdesc = validated_data.get('shiftdesc',instance.shiftdesc) 
        instance.dayname = validated_data.get('dayname',instance.dayname) 
        instance.dayno = validated_data.get('dayno',instance.dayno) 
        instance.offin_f = validated_data.get('offin_f',instance.offin_f) 
        instance.offout_f = validated_data.get('offout_f',instance.offout_f) 

当我这样选择时,将显示错误消息

When I select like that, Error message show

尝试获取字段 dayno 的值时出现KeyError错误序列化程序 ShiftSerializer .\ n序列化程序字段可能命名为错误地匹配并且不匹配 dict 上的任何属性或键实例.\ n原始异常文本为:"dayno"."

"Got KeyError when attempting to get a value for field dayno on serializer ShiftSerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the dict instance.\nOriginal exception text was: 'dayno'."

我只想选择 shiftid shiftdesc dayname ,如何仅选择这三个字段,我是否需要创建新的序列化器?

I would like to select the shiftid , shiftdesc and dayname only, How to select these three field only and am I need to create new serializer?

推荐答案

您的 ShiftSerializer 使用 __ all __ ,这意味着它将尝试序列化您的所有字段模型.

Your ShiftSerializer uses __all__, which means it is going to try to serialize all the fields in your model.

由于您指定的查询集未包含您的所有字段(并且是总和/不同,因此不应该包含所有字段),因此保证此操作将失败.

Since the queryset you have specified doesn't include all your fields (and it is a sum/distinct, so it should not), then this is guaranteed to fail.

有2个选项

1)仅为所需的字段创建一个新的序列化器,手动指定它们

1) Create a new serializer for only the fields you want, manually specifying them

class ShiftSum(Serializer):  # NOT model serializer
    shiftid = CharField()
    ... add other fields

return Response(ShiftSum(query, many=True).data)

2)将查询集转换为列表,然后直接将其返回

2) Convert the queryset to a list, and just return it directly

data = list(query) # turns your queryset into [{"shiftid":"n", ...}, ]
return Response(data=data)

如果从查询中获得的数据已经是您想要的格式,并且已经是用于简单JSON序列化的正确类型(没有日期时间,没有 Decimal 等),则这最后一种方法有效.试试看,看看是否可行.

This last way works if the data coming out of your query is already the format you want, and already the correct type for simple JSON serialization (no datetimes, no Decimal, etc). Try it and see if it works.

这篇关于如何仅在Viewset Django中选择指定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆