我有一个泛型函数,它迭代给定对象的_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)
答案 0 :(得分:17)
他们在self._meta.many_to_many
答案 1 :(得分:4)
如果要获取模型中的所有字段名称。您不需要使用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 "+"
"""