python - 对 DRF 序列化程序上的 ManyToMany 和 OneToMany 字段使用自定义模型管理器

标签 python django django-rest-framework

我已覆盖默认模型管理器 objects 以仅返回 is_deleted 不为 True 的对象。

+------+------------+
| Name | is_deleted |  
+------+------------+
| foo  | True       |  
| bar  | False      |  
| baz  | False      |  
+------+------------+

So, whenever I do MyModel.objects.all() gives me -

+------+------------+
| Name | is_deleted |  
+------+------------+
| bar  | False      |  
| baz  | False      |  
+------+------------+

But ManyToMany field is not respecting my objects manager. When I do user.foo_set.all(), I get all the objects, which I don't want. Is there a way around to do it?

I know that I can do user.foo_set(manager='objects').all() and it'll pick my object manager and give only the non deleted items but here's the problem -

I'm using Django Rest Framework and for serializing ToMany fields, it would give me all objects, regardless of their is_deleted value. Is there a way to enforce the object manager on the serializer for ToMany fields?

Right now, I'm using this, which seems kind of hack-ish -

class MySerializer(serializers.HyperlinkedModelSerializer):
    things = serializers.SerializerMethodField()

    class Meta:
        model = MyModel
        fields = ('id', 'things')

    def get_things(self, obj):
        return many_field_serialize(obj, 'things', ThingSerializer)





def many_field_serialize(obj, field_name, serializer_class):
    """
    Serializer, by default would give us all the related results, while we
    want to ignore the ones which have been marked as deleted or archived.
    We have our custom modele manager for that - `objects` but serializer
    doesn't use that. So the only solution at this time seems to manually
    get all the related fields and apply our `objects` model manager on it.

    There should be a better way to do it, or we'll keep duplicating this
    logic for every related field serializer.
    """
    items = getattr(obj, field_name)(manager='objects').all()
    serialized_items = serializer_class(
        instance=items, many=True
    )
    return serialized_items.data

最佳答案

终于明白了。我所要做的就是使 objects 模型管理器默认(通过将其定义为模型中的第一个管理器),并在模型管理器中设置 use_for_related_fields = True,这样默认情况下,相关字段将使用您的基本模型管理器。

关于python - 对 DRF 序列化程序上的 ManyToMany 和 OneToMany 字段使用自定义模型管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36530367/

相关文章:

python - 接下来 "n"每个产品的销售天数

python - 在 django settings.py 中包含应用程序

Django 本地化 : labels don't get updated

python - Django Admin 显示来自 Imagefield 的图像

Django 休息框架 : Set Permissions for function view

python - wxPython:如何固定网格调整器的一部分的大小

python - Paramiko - 不兼容的 SSH 服务器(没有可接受的 Mac)

python - 初学者Python书籍教程问题

python - django unicode 转换为日语

django-rest-framework - “QuerySet”对象没有属性 'pk'