Pickels
Pickels

Reputation: 34630

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

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.

Upvotes: 8

Views: 8175

Answers (4)

Keval
Keval

Reputation: 773

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

Upvotes: 0

jackotonye
jackotonye

Reputation: 3853

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

Upvotes: 0

Alireza Savand
Alireza Savand

Reputation: 3488

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!

Upvotes: 5

Pickels
Pickels

Reputation: 34630

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.

Upvotes: 13

Related Questions