我有两个模型,Person
和Appointment
。 Person
有很多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"
}
]
}
]
答案 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',)