Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

manytomany fields not visible in _meta.fields

Tags:

django

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)
like image 825
jerrymouse Avatar asked Dec 20 '11 08:12

jerrymouse


2 Answers

They are in self._meta.many_to_many

like image 171
DrTyrsa Avatar answered Nov 15 '22 13:11

DrTyrsa


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 "+"
    """
like image 25
Cloud Avatar answered Nov 15 '22 13:11

Cloud