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.

Pickels
  • 33,902
  • 26
  • 118
  • 178

4 Answers4

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.

Pickels
  • 33,902
  • 26
  • 118
  • 178
  • Given that in the django code (at ver 1.10) it is implemented a similar way, there is no more elegant solution... – Dmitry Jan 24 '18 at 13:07
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!

robjohncox
  • 3,639
  • 3
  • 25
  • 51
Alireza Savand
  • 3,462
  • 3
  • 26
  • 36
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
jackotonye
  • 3,537
  • 23
  • 31
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
Keval
  • 557
  • 10
  • 15