Django REST Framework一对多相关的字段数据插入和过滤

时间:2016-11-04 05:09:08

标签: python django django-rest-framework

我有两个模型,PersonAppointmentPerson有很多Appointment

models.py

class Person(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField()

    def __str__(self):
        return self.name


class Appointment(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='appointments')
    date = models.DateField(unique=True)

    class Meta:
        ordering = 'date',

    def __str__(self):
        return str(self.date)

和我的serializers.py文件是:

from rest_framework import serializers
from appointment.models import Person, Appointment


class AppointmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Appointment
        fields = ('date',)


class PersonSerializer(serializers.ModelSerializer):
    appointments = AppointmentSerializer(many=True)

    class Meta:
        model = Person
        fields = ('name', 'email', 'appointments',)

    def create(self, validated_data):
        appointments_data = validated_data.pop('appointments')
        person = Person.objects.create(**validated_data)
        for appointment_data in appointments_data:
            Appointment.objects.create(person=person, **appointment_data)
        return person

最后我的观点是:

class PersonViewSet(viewsets.ModelViewSet):
    serializer_class = PersonSerializer
    queryset = Person.objects.all()
    filter_backends = [DjangoFilterBackend]
    filter_fields = ['name', 'appointments']

这将person_list作为我的期望返回:

    [
 {
        "name": "Arif Hasan",
        "email": "arif@gmail.com",
        "appointments": [
            {
                "date": "2016-10-10"
            },
            {
                "date": "2016-10-17"
            },
            {
                "date": "2016-11-07"
            }
        ]
    },
    {
        "name": "Atanu Shome",
        "email": "atanu@gmail.com",
        "appointments": [
            {
                "date": "2016-11-13"
            }
        ]
    }
    ]
  • 但我不能在这里创建新的约会。
  • 无法按日期范围过滤人。

1 个答案:

答案 0 :(得分:0)

您应该使用元组指定filter_backends,filter_fields。 您还希望按日期字段进行过滤,因此您必须在仅appointments__date内嵌的filter_fields中指定appointments

您应该将视图集定义如下:

class PersonViewSet(viewsets.ModelViewSet):
    serializer_class = PersonSerializer
    queryset = Person.objects.all()
    filter_backends = (DjangoFilterBackend,)
    filter_fields = ('name', 'appointments__date',)

检查:Django filtering