django遍历model里面的属性字段

2025-04-23 19:25:43
推荐回答(2个)
回答1:

具体的写法是

results = ServerInformation.objects.get(id = 1)#filter是queryset,没有_meta方法
allhost = ServerInformation._meta.get_all_field_names()#这句没错
vername = ServerInformation._meta.get_field('ServerType').verbose_name#这句也没错,S erverType是该模型的一个属性。
vervalue = ServerInformation._meta.get_field('ServerZone').default #即可获取到默认的值,话说你都懂得获取到verbose_name,怎么不会想到直接.default呢。

ps:

getattr(object, name[, default])

  Return the value of the named attribute of object.  name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example,

getattr(x, 'foobar')

 is equivalent to

 x.foobar

. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

看看怎么使用。

回答2:

补充一下:我用的1.11版本的jango,ServerInformation._meta.get_fields() 这样取到所有字段