Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to introspect django model fields?

I am trying to obtain class information on a field inside a model, when I only know name of the field and name of the model (both plain strings). How is it possible?

I can load the model dynamically:

from django.db import models model = models.get_model('myapp','mymodel') 

Now I have field - 'myfield' - how can I get the class of that field?

If the field is relational - how to get related field?

Thanks a bunch!

like image 445
Evgeny Avatar asked Mar 05 '10 03:03

Evgeny


People also ask

What is_ meta in django?

Model Meta is basically the inner class of your model class. Model Meta is basically used to change the behavior of your model fields like changing order options,verbose_name, and a lot of other options. It's completely optional to add a Meta class to your model.

What is def __ str __( self in Django?

def str(self): is a python method which is called when we use print/str to convert object into a string. It is predefined , however can be customised.

What does @property do in Django?

In Python, the @property decorator allows you to call custom model methods as if they were normal model attributes. For example, if you have the following greeting method, class Person: def __init__(self, first_name): self.


1 Answers

You can use model's _meta attribute to get field object and from field you can get relationship and much more e.g. consider a employee table which has a foreign key to a department table

In [1]: from django.db import models  In [2]: model = models.get_model('timeapp', 'Employee')  In [3]: dep_field = model._meta.get_field_by_name('department')  In [4]: dep_field[0].target_field Out[4]: 'id'  In [5]: dep_field[0].related_model Out[5]: <class 'timesite.timeapp.models.Department'> 

from django/db/models/options.py

def get_field_by_name(self, name):     """     Returns the (field_object, model, direct, m2m), where field_object is     the Field instance for the given name, model is the model containing     this field (None for local fields), direct is True if the field exists     on this model, and m2m is True for many-to-many relations. When     'direct' is False, 'field_object' is the corresponding RelatedObject     for this field (since the field doesn't have an instance associated     with it).      Uses a cache internally, so after the first access, this is very fast.     """ 
like image 68
Anurag Uniyal Avatar answered Sep 20 '22 13:09

Anurag Uniyal