gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:13:33 25 4
gpt4 key购买 nike

我已覆盖默认模型管理器 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com