1

我们需要帮助

我如何实现以下...

在这里,我有两个模型 example1 和 example2,因为我已经使用序列化器加入了两个表,现在我想在 example2serializer 或 example2viewsets 中使用字段 (patient_n_key,centre_master_short_name) 进行过滤

模型.py

class Example1(models.Model):

    patient_id = models.AutoField(primary_key=True)
    patient_n_key = models.CharField(max_length=15, blank=True, unique=True)
    centre_master_short_name = models.CharField(blank=False, max_length=33)

    class Meta:
        managed = False
        ordering = ['patient_id']
        db_table = 'example1'

class Example2(models.Model):

    appointment_id = models.AutoField(primary_key=True)
    appointment_n_key = models.CharField(max_length=15, blank=True)
    patient_n_key = models.ForeignKey('Example1', 
    db_column='patient_n_key', to_field='patient_n_key', 
    on_delete=models.CASCADE, related_name="Example2_id")
    centre_master_short_name = models.CharField(blank=False, max_length=33)

    class Meta:
        managed = False
        ordering = ['appointment_id']
        db_table = 'example2'

序列化程序1.py

class Example1serializer(serializers.ModelSerializer):
    class Meta:
        model=models.Example1
        fields='__all__'   

class Example2Serializer(serializers.ModelSerializer):
patient_n_key = Example1serializer(read_only=True)
    class Meta:
        model=models.Example2
        fields='__all__'

视图.py

class Example1viewset(viewsets.ModelViewSet):
    queryset=models.Example1.objects.all()
    serializer_class=serializers1.Example1serializer
    lookup_field = 'patient_n_key'

class Example2viewset(viewsets.ModelViewSet):
    queryset=models.Example2.objects.all()
    serializer_class=serializers1.Example2serializer
    lookup_field = 'appointment_n_key'

网址.py

router.register(r'example1', views.Example1viewset, 
base_name='example1')
router.register(r'example2', views.Example2viewset, 
base_name='example2')

如何在 django rest 框架中使用视图集进行过滤?或者,如果有任何其他首选方式,请列出。谢谢你。

4

1 回答 1

0

您可以为此使用 django-filtes 库

class Example1viewset(viewsets.ModelViewSet):
    queryset=models.Example1.objects.all()
    serializer_class=serializers1.Example1serializer
    lookup_field = 'patient_n_key'
    filter_backends = (DjangoFilterBackend)
    filter_fields = ('centre_master_short_name','patient_n_key')
于 2018-11-26T11:12:39.863 回答