python Django活塞:如何获得应用程序标签+型号名称?

k10s72fa  于 2023-01-19  发布在  Python
关注(0)|答案(4)|浏览(118)

之前我只是使用内置的django序列化器,它添加了一个model字段。

{
    pk: 1
    model: "zoo.cat"
}

如何使用django-piston得到相同的模型字段?
我尝试了fields =('id','model'),但没有成功。

nwwlzxa7

nwwlzxa71#

添加到我的模型:

def model(self):
    return "{0}.{1}".format(self._meta.app_label, self._meta.object_name).lower()

然后把这个传给我的BaseHandler:

fields = ('id', 'model')

看起来很有效。如果有人有其他的解决方案,请随时发布。

t1rydlwq

t1rydlwq2#

作为app_label的代码:

instance._meta.app_label

对于model_name

instance.__class__.__name__

并与get_model可以得到模型名称从字符串或url!

tp5buhyn

tp5buhyn3#

最好使用 metaOptions.label
https://docs.djangoproject.com/en/2.1/ref/models/options/#label

MyModel._meta.label  # app_name.MyModel
MyModel._meta.label_lower  # app_name.mymodel
ee7vknir

ee7vknir4#

参考:Alireza Savand's answer

from django.apps import apps

def get_app_label_and_model_name(instance: object):
"""
    get_model(), which takes two pieces of information — an “app label” and “model name” — and returns the model
     which matches them.
@return: None / Model
"""
app_label = instance._meta.app_label
model_name = instance.__class__.__name__
model = apps.get_model(app_label, model_name)
return model

如何使用?

model_name = get_app_label_and_model_name(pass_model_object_here)

并使用它来获取查询的动态模型名称

model_name = get_app_label_and_model_name(pass_model_object_here)
query_set = model_name.objects.filter() # or anything else

相关问题