我有一个泛型函数,迭代给定对象的_meta.fields.除ManyToMany字段外,所有字段名称和值都被正确获取.它似乎完全忽略了ManyToMany字段.我们如何从m2m字段中检索fks?
def myfunc(self)
for field in self._meta.fields:
type = field.get_internal_type()
name = field.name
val = getattr(self,field.name)
Run Code Online (Sandbox Code Playgroud)
DrT*_*rsa 17
他们在 self._meta.many_to_many
如果要获取模型中的所有字段名称。您不需要使用self._meta.many_to_many + self._meta.fields.
你可以只使用[field.name for field in model._meta.get_fields()].
请注意,get_fields将返回所有字段(包括多对多和外键)
Django get_fields:
def get_fields(self, include_parents=True, include_hidden=False):
"""
Returns a list of fields associated to the model. By default, includes
forward and reverse fields, fields derived from inheritance, but not
hidden fields. The returned fields can be changed using the parameters:
- include_parents: include fields derived from inheritance
- include_hidden: include fields that have a related_name that
starts with a "+"
"""
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1428 次 |
| 最近记录: |