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

4

8

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.

Wayless answered 15/3, 2011 at 19:40 Comment(0)
W
13

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.

Wayless answered 15/3, 2011 at 21:25 Comment(1)
Given that in the django code (at ver 1.10) it is implemented a similar way, there is no more elegant solution...Fossick
A
5

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!

Aerometeorograph answered 14/4, 2011 at 12:26 Comment(0)
A
0

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
Almagest answered 17/11, 2018 at 14:36 Comment(0)
V
0

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
Viator answered 19/1, 2023 at 7:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.