MENU

django rest-framework DRF 逗分筛选

June 5, 2023 • 学习

有多对多模型

class GeneralTagValue(models.Model):
    pass

class Job(models.Model):
    general_tags = models.ManyToManyField(
        GeneralTagValue,
        verbose_name=_('GeneralTags'),
        blank=True,
        help_text=_('GeneralTags'),
        related_name="job_set",
        related_query_name="jobs",
    )

并有这样的一个ViewSet

class JobViewSet(viewsets.GenericViewSet,
                 mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin):
    queryset = Job.objects.all().order_by('id')
    filterset_class = JobFilter
    serializer_class = JobSerializer
    permission_classes = [AllowAny]

关键点在于JobFilter的编写上

class JobFilter(filters.FilterSet):
    general_tags = filters.ModelMultipleChoiceFilter(
        queryset=GeneralTagValue.objects.all(),
        field_name='general_tags',
        to_field_name='id',
        widget=CSVWidget
    )

    class Meta:
        model = models.Job
        fields = ('general_tags')

关键点在于:CSVWidget

Archives QR Code
QR Code for this page
Tipping QR Code