简体   繁体   中英

How to serialize distinct queryset in django rest framework?

I have a model that handles Italian's VAT rates. There are three types of rate: 'Ordinaria', 'Ridotta', 'Minima' each type of rate can store multiple values according to a date. For example the current rate for ordinary VAT is 22% and has been set on the 1st oct 2013 but rates have changed during time and I need to store changes and to retrieve the three rates according to a specific date.

The model to describe rates is called AliquoteIVA . I use a custom manager to retrieve the current rates as of today or by providing a specific date:

class AliquoteIVAManager(models.Manager):
    def current(self, data):
        return self.filter(data__lte=data) \
                    .order_by('descrizione', '-data') \
                    .distinct('descrizione')


class AliquoteIVA(models.Model):
    """ Modello delle aliquote IVA """
    data = models.DateField(
        blank = False,
    )

    descrizione = models.CharField(
        blank = False,
        max_length = 1,
        default = IVA.IVA_ORDINARIA,
        choices = IVA.IVA_TIPOLOGIA_CHOICES,
    )

    aliquota = models.DecimalField(
        blank = False,
        null = False,
        default = '0',
        max_digits=19,
        decimal_places = 2,
        validators = [MinValueValidator(0.0)],
    )

    objects = AliquoteIVAManager()

    def __str__(self):
        str_aliquota = "{0:.2f}".format(self.aliquota).replace('.', ',')

        return "IVA {descrizione} al {aliquota}% in vigore dal {data}".format(
            descrizione=self.get_descrizione_display(),
            aliquota=str_aliquota,
            data=self.data
            )

    class Meta:
        ordering = ('-data', 'aliquota',)
        verbose_name = 'Aliquota IVA'
        verbose_name_plural = 'Aliquote IVA'

I've tested the querysets and everything works fine:

AliquoteIVA.objects.all() will return:

<QuerySet [
  <AliquoteIVA: IVA Ordinaria al 26,50% in vigore dal 2021-01-01>, 
  <AliquoteIVA: IVA Ridotta al 13,00% in vigore dal 2020-01-01>,
  <AliquoteIVA: IVA Ordinaria al 25,20% in vigore dal 2020-01-01>,
  <AliquoteIVA: IVA Minima al 4,00% in vigore dal 2013-10-01>,
  <AliquoteIVA: IVA Ridotta al 10,00% in vigore dal 2013-10-01>,
  <AliquoteIVA: IVA Ordinaria al 22,00% in vigore dal 2013-10-01>,
  <AliquoteIVA: IVA Ordinaria al 20,00% in vigore dal 1997-10-01>,
  <AliquoteIVA: IVA Ordinaria al 19,00% in vigore dal 1988-08-01>,
  <AliquoteIVA: IVA Ordinaria al 18,00% in vigore dal 1982-08-05>
]>

AliquoteIVA.objects.current('2019-10-17') will return:

<QuerySet [
  <AliquoteIVA: IVA Minima al 4,00% in vigore dal 2013-10-01>,
  <AliquoteIVA: IVA Ordinaria al 22,00% in vigore dal 2013-10-01>,
  <AliquoteIVA: IVA Ridotta al 10,00% in vigore dal 2013-10-01>
]>

Everything works as expected but I need to set a serializer and some api endpoint to use these rates in a client.

The serializer for AliquoteIVA is pretty simple:

class AliquoteIVASerializer(serializers.ModelSerializer):
    """
    Serializer per le aliquote IVA
    """
    class Meta:
        model = AliquoteIVA
        fields = '__all__'
        read_only_fields = [
            'id'
            ]

I've set two views:

  • the first one AliquoteIVAViewset will provide api endpoints to CURD rates.
  • the last one CurrentAliquoteIVAView will just provide a generic read-only list api view to display the current rates.
class AliquoteIVAViewset(viewsets.ModelViewSet):
    """
    API endpoint per le aliquote IVA
    """

    queryset = AliquoteIVA.objects.all()
    serializer_class = AliquoteIVASerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    filter_backends = [filters.SearchFilter]
    search_fields = ['descrizione']


class CurrentAliquoteIVAView(generics.ListAPIView):
    """
    API endpoint per vedere le aliquote IVA correnti in data odierna
    o in base a una data specifica (Y-m-d)
    """

    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    filter_backends = [filters.SearchFilter]
    search_fields = ['descrizione']

    def get(self, request, data=None, format=None):
        qdata = data if data is not None else datetime.today()

        queryset = AliquoteIVA.objects.current(qdata)
        return Response(queryset)

The first view is handled by a router in urls, the second one is explicitly set in urls and require a paramenter data

router = routers.DefaultRouter()
router.register(r'aliquote/iva', views.AliquoteIVAViewset)


aliquote_iva_patterns = [
    path('', views.CurrentAliquoteIVAView.as_view()),
    path('<str:data>', views.CurrentAliquoteIVAView.as_view()),
]


urlpatterns = [
    path('aliquote/iva/corrente/', include(aliquote_iva_patterns)),
    path('', include(router.urls))
]

The first view (the viewset) works as expected, but when I try to reach the api endpoint to show the list of current rates, django raise an error:

Exception Type: TypeError
Exception Value:    
Object of type 'AliquoteIVA' is not JSON serializable

Why is AliquoteIVA.objects.current('2019-10-17') a non serializable object?

How can I serialize the current queryset?

By defining get you've bypassed all the functionality of DRF. In particular, you aren't calling the serializer, which is responsible for converting the object into a serializable form.

This logic should go into get_queryset , not get .

class CurrentAliquoteIVAView(generics.ListAPIView):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    filter_backends = [filters.SearchFilter]
    search_fields = ['descrizione']
    serializer_class = AliquoteIVASerializer

    def get_queryset(self):
        qdata = self.kwargs.get('data', datetime.today())
        queryset = AliquoteIVA.objects.current(qdata)
        return queryset

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM