120π
As most of answers are outdated Iβll try to update you on Django 2.2
Here posts- your app (posts, blog, shop, etc.)
1) From model link: https://docs.djangoproject.com/en/stable/ref/models/meta/
from posts.model import BlogPost
all_fields = BlogPost._meta.fields
#or
all_fields = BlogPost._meta.get_fields()
Note that:
all_fields=BlogPost._meta.get_fields()
Will also get some relationships, which, for ex: you can not display in a view.
As in my case:
Organisation._meta.fields
(<django.db.models.fields.AutoField: id>, <django.db.models.fields.DateField: created>...
and
Organisation._meta.get_fields()
(<ManyToOneRel: crm.activity>, <django.db.models.fields.AutoField: id>, <django.db.models.fields.DateField: created>...
2) From instance
from posts.model import BlogPost
bp = BlogPost()
all_fields = bp._meta.fields
3) From parent model
Letβs suppose that we have Post as the parent model and you want to see all the fields in a list, and have the parent fields to be read-only in Edit mode.
from django.contrib import admin
from posts.model import BlogPost
@admin.register(BlogPost)
class BlogPost(admin.ModelAdmin):
all_fields = [f.name for f in Organisation._meta.fields]
parent_fields = BlogPost.get_deferred_fields(BlogPost)
list_display = all_fields
read_only = parent_fields
378π
Django versions 1.8 and later:
You should use get_fields()
:
[f.name for f in MyModel._meta.get_fields()]
The get_all_field_names()
method is deprecated starting from Django
1.8 and will be removed in 1.10.
The documentation page linked above provides a fully backwards-compatible implementation of get_all_field_names()
, but for most purposes the previous example should work just fine.
Django versions before 1.8:
model._meta.get_all_field_names()
That should do the trick.
That requires an actual model instance. If all you have is a subclass of django.db.models.Model
, then you should call myproject.myapp.models.MyModel._meta.get_all_field_names()
- [Django]-How can I filter a Django query with a list of values?
- [Django]-How to change User representation in Django Admin when used as Foreign Key?
- [Django]-Specifying limit and offset in Django QuerySet wont work
82π
The get_all_related_fields()
method mentioned herein has been deprecated in 1.8. From now on itβs get_fields()
.
>> from django.contrib.auth.models import User
>> User._meta.get_fields()
- [Django]-How to monkey patch Django?
- [Django]-With DEBUG=False, how can I log django exceptions to a log file
- [Django]-Numeric for loop in Django templates
59π
I find adding this to django models quite helpful:
def __iter__(self):
for field_name in self._meta.get_all_field_names():
value = getattr(self, field_name, None)
yield (field_name, value)
This lets you do:
for field, val in object:
print field, val
- [Django]-What is a "django backend"?
- [Django]-How do I install psycopg2 for Python 3.x?
- [Django]-How to force Django models to be released from memory
16π
This does the trick. I only test it in Django 1.7.
your_fields = YourModel._meta.local_fields
your_field_names = [f.name for f in your_fields]
Model._meta.local_fields
does not contain many-to-many fields. You should get them using Model._meta.local_many_to_many
.
- [Django]-Has Django served an excess of 100k daily visits?
- [Django]-Django REST Framework : "This field is required." with required=False and unique_together
- [Django]-PyCharm: DJANGO_SETTINGS_MODULE is undefined
14π
It is not clear whether you have an instance of the class or the class itself and trying to retrieve the fields, but either way, consider the following code
Using an instance
instance = User.objects.get(username="foo")
instance.__dict__ # returns a dictionary with all fields and their values
instance.__dict__.keys() # returns a dictionary with all fields
list(instance.__dict__.keys()) # returns list with all fields
Using a class
User._meta.__dict__.get("fields") # returns the fields
# to get the field names consider looping over the fields and calling __str__()
for field in User._meta.__dict__.get("fields"):
field.__str__() # e.g. 'auth.User.id'
- [Django]-Django: show the count of related objects in admin list_display
- [Django]-Django 1.5 custom User model error. "Manager isn't available; User has been swapped"
- [Django]-Running Django with FastCGI or with mod_python
14π
A detail not mentioned by others:
[f.name for f in MyModel._meta.get_fields()]
get, for example
['id', 'name', 'occupation']
and
[f.get_attname() for f in MyModel._meta.get_fields()]
get
['id', 'name', 'occupation_id']
If
reg = MyModel.objects.first()
then
reg.occupation
get, for example
<Occupation: Dev>
and
reg.occupation_id
get
1
- [Django]-ImportError: Failed to import test module:
- [Django]-Copy a database column into another in Django
- [Django]-Django-taggit β how do I display the tags related to each record
12π
def __iter__(self):
field_names = [f.name for f in self._meta.fields]
for field_name in field_names:
value = getattr(self, field_name, None)
yield (field_name, value)
This worked for me in django==1.11.8
- [Django]-Django: show the count of related objects in admin list_display
- [Django]-What's the difference between select_related and prefetch_related in Django ORM?
- [Django]-POST jQuery array to Django
8π
MyModel._meta.get_all_field_names()
was deprecated several versions back and removed in Django 1.10.
Hereβs the backwards-compatible suggestion from the docs:
from itertools import chain
list(set(chain.from_iterable(
(field.name, field.attname) if hasattr(field, 'attname') else (field.name,)
for field in MyModel._meta.get_fields()
# For complete backwards compatibility, you may want to exclude
# GenericForeignKey from the results.
if not (field.many_to_one and field.related_model is None)
)))
- [Django]-How to deal with "SubfieldBase has been deprecated. Use Field.from_db_value instead."
- [Django]-How to convert JSON data into a Python object?
- [Django]-Fastest way to get the first object from a queryset in django?
7π
Just to add, I am using self object, this worked for me:
[f.name for f in self.model._meta.get_fields()]
- [Django]-How to get an ImageField URL within a template?
- [Django]-How to debug in Django, the good way?
- [Django]-Uninstall Django completely
7π
At least with Django 1.9.9 β the version Iβm currently using β, note that .get_fields()
actually also βconsidersβ any foreign model as a field, which may be problematic. Say you have:
class Parent(models.Model):
id = UUIDField(primary_key=True)
class Child(models.Model):
parent = models.ForeignKey(Parent)
It follows that
>>> map(lambda field:field.name, Parent._model._meta.get_fields())
['id', 'child']
while, as shown by @Rockallite
>>> map(lambda field:field.name, Parent._model._meta.local_fields)
['id']
- [Django]-Django F() division β How to avoid rounding off
- [Django]-Whats the difference between using {{STATIC_URL}} and {% static %}
- [Django]-Django's Double Underscore
6π
So before I found this post, I successfully found this to work.
Model._meta.fields
It works equally as
Model._meta.get_fields()
Iβm not sure what the difference is in the results, if there is one. I ran this loop and got the same output.
for field in Model._meta.fields:
print(field.name)
- [Django]-How do I deploy Django on AWS?
- [Django]-How to get the current URL within a Django template?
- [Django]-Django-rest-framework returning 403 response on POST, PUT, DELETE despite AllowAny permissions
0π
In sometimes we need the db columns as well:
def get_db_field_names(instance):
your_fields = instance._meta.local_fields
db_field_names=[f.name+'_id' if f.related_model is not None else f.name for f in your_fields]
model_field_names = [f.name for f in your_fields]
return db_field_names,model_field_names
Call the method to get the fields:
db_field_names,model_field_names=get_db_field_names(Mymodel)
- [Django]-Macros in django templates
- [Django]-Stack trace from manage.py runserver not appearing
- [Django]-How to submit form without refreshing page using Django, Ajax, jQuery?
0π
Combined multiple answers of the given thread (thanks!) and came up with the following generic solution:
class ReadOnlyBaseModelAdmin(ModelAdmin):
def has_add_permission(self, request):
return request.user.is_superuser
def has_delete_permission(self, request, obj=None):
return request.user.is_superuser
def get_readonly_fields(self, request, obj=None):
return [f.name for f in self.model._meta.get_fields()]
- [Django]-Django-Bower + Foundation 5 + SASS, How to configure?
- [Django]-Suppress "?next=blah" behavior in django's login_required decorator
- [Django]-Django-allauth social account connect to existing account on login
0π
You can try this script to get the model and itβs consecutive fields in a dictionary.
Furthermore, this can also reduce the hectic manual work of writing db schemas.
import json
from django.apps import apps
from django.http import HttpResponse
def index(request):
models = {
model.__name__: model for model in apps.get_models()
}
resp_data = []
def get_field_names(model_class):
return [f.name for f in model_class._meta.fields]
for model in models:
all_fields = get_field_names(models[model])
model_dict = {
model : all_fields
}
resp_data.append(model_dict)
data = {
'data' : resp_data
}
return HttpResponse(json.dumps(data), content_type='application/json')
- [Django]-How to get superuser details in Django?
- [Django]-Django-way for building a "News Feed" / "Status update" / "Activity Stream"
- [Django]-Change a field in a Django REST Framework ModelSerializer based on the request type?
-2π
Why not just use that:
manage.py inspectdb
Example output:
class GuardianUserobjectpermission(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
object_pk = models.CharField(max_length=255)
content_type = models.ForeignKey(DjangoContentType, models.DO_NOTHING)
permission = models.ForeignKey(AuthPermission, models.DO_NOTHING)
user = models.ForeignKey(CustomUsers, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'guardian_userobjectpermission'
unique_together = (('user', 'permission', 'object_pk'),)
- [Django]-Django error when installing Graphite β settings.DATABASES is improperly configured. Please supply the ENGINE value
- [Django]-Strings won't be translated in Django using format function available in Python 2.7
- [Django]-Django limit_choices_to for multiple fields with "or" condition