| 171 | |
| 172 | ===== get_field |
| 173 | |
| 174 | {{{ |
| 175 | def get_field(self, field_name, m2m=True, data=True, related_m2m=False, related_objects=False, virtual=False) |
| 176 | }}} |
| 177 | |
| 178 | 'get_field' returns a field_instance from a given field name. field_name can be anything from name, attname and related_query name. |
| 179 | get_field is recursive by default and does not include any hidden or proxied relations. There has still not been any reason to add these |
| 180 | and they can be derived from 'get_fields'. |
| 181 | If a given name is not found, it will raise a FieldDoesNotExist error. |
| 182 | 'get_field' is internally cached and gets all field information from 'get_fields' internally. |
| 183 | |
| 184 | NOTE: There is an inconsistency between the defaults of get_field and get_fields. 'get_fields' by default enables only data fields |
| 185 | while 'get_field' by default enables data and m2m. This is because of backwards-compatibility issues (get_field already existed). |
| 186 | |
| 187 | {{{ |
| 188 | >>> User._meta.get_new_field('username') # A data field |
| 189 | <django.db.models.fields.CharField: username> |
| 190 | |
| 191 | >>> User._meta.get_new_field('logentry', related_objects=True) # A related object |
| 192 | <RelatedObject: admin:logentry related to user> |
| 193 | |
| 194 | >>> LogEntry._meta.get_field('user') # ForeignKey can be queried by field name |
| 195 | <django.db.models.fields.related.ForeignKey: user> |
| 196 | >>> LogEntry._meta.get_field('user_id') # .. and also by database column name |
| 197 | <django.db.models.fields.related.ForeignKey: user> |
| 198 | |
| 199 | >>> User._meta.get_new_field('does_not_exist') # A non existent field |
| 200 | *** FieldDoesNotExist: User has no field named 'does_not_exist' |
| 201 | }}} |