I would like to select the distinct field and some field only from Django ViewSet.
My method
@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)
My Model
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)
.
.
.
My serializer
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
"Got KeyError when attempting to get a value for field
dayno
on serializerShiftSerializer
.\nThe serializer field might be named incorrectly and not match any attribute or key on thedict
instance.\nOriginal exception text was: 'dayno'."
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?