在_meta.fields中看不到多个字段

jer*_*use 6 django

我有一个泛型函数,迭代给定对象的_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

  • 从[source](https://docs.djangoproject.com/zh-CN/2.1/_modules/django/db/models/options/#Options)获取`_meta.many_to_many`属性:“ * Private API *仅用于由Django本身使用;`get_fields()`与字段属性过滤结合在一起是用于获取此列表的“公共API”。” (2认同)

Sim*_*Jie 6

如果要获取模型中的所有字段名称。您不需要使用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)