【问题标题】:Use custom model manager for ManyToMany and OneToMany fields on DRF serializer对 DRF 序列化程序上的 ManyToMany 和 OneToMany 字段使用自定义模型管理器
【发布时间】:2016-04-10 13:26:48
【问题描述】:

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

+--------+------------+ |姓名 | is_deleted | +--------+------------+ |富 |真 | |酒吧 |假 | |巴兹 |假 | +--------+------------+

所以,每当我这样做时,MyModel.objects.all() 都会给我 -

+--------+------------+ |姓名 | is_deleted | +--------+------------+ |酒吧 |假 | |巴兹 |假 | +--------+------------+

但是ManyToMany 字段不尊重我的objects 经理。当我做user.foo_set.all() 时,我得到了所有我不想要的对象。有办法解决吗?

我知道我可以做到user.foo_set(manager='objects').all(),它会选择我的对象管理器并只提供未删除的项目,但问题是 -

我正在使用 Django Rest Framework 并序列化 ToMany 字段,它会给我所有对象,无论它们的 is_deleted 值如何。有没有办法在ToMany 字段的序列化程序上强制执行对象管理器?

现在,我正在使用它,这似乎有点 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

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 2021-12-15
      • 2016-08-17
      • 2021-03-19
      • 2017-02-04
      • 1970-01-01
      相关资源
      最近更新 更多