Django-piston: How can I get app_label + model_name?

Question:

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.

Asked By: Pickels

||

Answers:

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.

Answered By: Pickels

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!

Answered By: Alireza Savand

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
Answered By: jackotonye

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
Answered By: Keval
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.