Before I was just using the build-in django serializers and it added a model field.
{
pk: 1
model: "zoo.cat"
}
How can I get the same model field using django-piston?
I tried fields = ('id', 'model') but that didn't work.
Before I was just using the build-in django serializers and it added a model field.
{
pk: 1
model: "zoo.cat"
}
How can I get the same model field using django-piston?
I tried fields = ('id', 'model') but that didn't work.
Added this to my model:
def model(self):
return "{0}.{1}".format(self._meta.app_label, self._meta.object_name).lower()
And this to my BaseHandler:
fields = ('id', 'model')
Seems to work. If anybody has other solutions feel free to post them.
As your code for app_label
:
instance._meta.app_label
for model_name
:
instance.__class__.__name__
and with get_model
can get model name from strings or url!
Better use the meta Options.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
reference: 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
How to use?
model_name = get_app_label_and_model_name(pass_model_object_here)
and use this to get dynamic model name for queries
model_name = get_app_label_and_model_name(pass_model_object_here)
query_set = model_name.objects.filter() # or anything else
© 2022 - 2024 — McMap. All rights reserved.