我已经定义了一个User类,它(最终)继承自models.Model。我想获得为这个模型定义的所有字段的列表。例如,phone_number = CharField(max_length=20)。基本上,我想检索从Field类继承的任何东西。

我认为我可以利用inspect.getmembers(model)来检索这些字段,但是它返回的列表不包含这些字段中的任何一个。看起来Django已经掌握了这个类,添加了它所有神奇的属性,并去掉了实际定义的内容。所以…我怎样才能得到这些田地?他们可能有一个功能来检索他们自己的内部目的?


当前回答

不清楚您拥有的是类的实例还是类本身,并试图检索字段,但无论哪种方式,考虑以下代码

使用实例

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

使用类

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'

其他回答

这里提到的get_all_related_fields()方法在1.8中已弃用。从现在开始,它是get_fields()。

>> from django.contrib.auth.models import User
>> User._meta.get_fields()

结合给定线程的多个答案(谢谢!),并提出以下通用解决方案:

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()]

有时候我们也需要db列:

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

调用该方法获取字段:

db_field_names,model_field_names=get_db_field_names(Mymodel)

这很管用。我只在Django 1.7中测试它。

your_fields = YourModel._meta.local_fields
your_field_names = [f.name for f in your_fields]

Model._meta。Local_fields不包含多对多字段。您应该使用Model._meta.local_many_to_many来获取它们。

不清楚您拥有的是类的实例还是类本身,并试图检索字段,但无论哪种方式,考虑以下代码

使用实例

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

使用类

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'