我有一个DRFAPI,它支持将作者的书包含在
authors
收到请求。
我们的API有一个软删除系统,书(2)被标记为已删除。
但当我提出以下要求时,第(2)册仍然包含在回复中。
我只想要一本书作为对这个请求的回应。
GET
http://localhost/authors/2?include=books
API返回给我:
{
"data": {
"type": "Author",
"id": "2",
"attributes": {...},
"relationships": {
"books": {
"meta": {
"count": 2
},
"data": [
{
"type": "Book",
"id": "1"
},
{
"type": "Book",
"id": "2"
}
]
}
}
},
"included": [
{
"type": "Book",
"id": "1",
"attributes": {...}
},
{
"type": "Book",
"id": "2",
"attributes": {...}
}
]
}
我有一个
BaseModel
处理覆盖
delete
方法:
class BaseModel(Model):
archive = BoolYesNoField(db_column="archive", default=False, null=False)
created = DateTimeField(db_column="created", auto_now_add=True, null=False)
updated = DateTimeField(db_column="updated", auto_now=True, null=False)
objects = BaseManager()
all_objects = BaseManager(alive_only=False)
def delete(self):
self.archive = True
self.save()
relate_obj_delete(self)
def hard_delete(self):
super(Model, self).delete()
def undelete(self):
self.archive = False
self.save()
经理
class BaseManager(Manager):
def __init__(self, *args, **kwargs):
self.alive_only = kwargs.pop("alive_only", True)
super(BaseManager, self).__init__(*args, **kwargs)
def get_queryset(self):
if self.alive_only:
return BaseQuerySet(self.model).filter(archive=False)
return BaseQuerySet(self.model)
def hard_delete(self):
return self.get_queryset().hard_delete()
AuthorViewSet
class AuthorViewSet(BaseViewSet):
queryset = Author.objects.all()
serializer_class = AuthorSerializer
filterset_class = AuthorFilterSet
序列化程序
class AuthorSerializer(BaseSerializer):
books = ResourceRelatedField(many=True, read_only=True)
included_serializers = {
"books": BookSerializer,
}
class Meta(BaseSerializer.Meta):
model = Author
如果有人能给我指出正确的方向,我会很有帮助。
可能有一个函数需要重写,但我似乎找不到它。