I have a generic function that iterates over _meta.fields of a given object. All field names and values are fetched correctly except for ManyToMany fields. It seems to completely ignore ManyToMany fields. How do we retrive the 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)
They are in self._meta.many_to_many
If you want to get all field names in a model. You don't 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 get_fields
will 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 "+"
"""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With