Multi-user fields are not displayed in _meta.fields

I have a generic function that iterates over the fields of a given object. All field names and values ​​are selected correctly, with the exception of ManyToMany fields. It seems to completely ignore the ManyToMany fields. How do we extract fks from m2m fields?

def myfunc(self)
    for field in self._meta.fields:
        type = field.get_internal_type()
        name = field.name
        val = getattr(self,field.name)
+5
source share
2 answers

They are in self._meta.many_to_many

+15
source

If you want to get all the field names in the model. You do not need to use self._meta.many_to_many + self._meta.fields.

You can just use [field.name for field in model._meta.get_fields()].

Note that it get_fieldswill return all fields (including many-to-many and foreign key)

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 "+"
    """
0
source

All Articles