标签云

微信群

扫码加入我们

WeChat QR Code

I've defined a User class which (ultimately) inherits from models.Model. I want to get a list of all the fields defined for this model. For example, phone_number = CharField(max_length=20). Basically, I want to retrieve anything that inherits from the Field class.I thought I'd be able to retrieve these by taking advantage of inspect.getmembers(model), but the list it returns doesn't contain any of these fields. It looks like Django has already gotten a hold of the class and added all its magic attributes and stripped out what's actually been defined. So... how can I get these fields? They probably have a function for retrieving them for their own internal purposes?


This might help, too pypi.python.org/pypi/django-inspect-model/0.5

2019年07月24日39分31秒

possible duplicate of Get model's fields in Django

2019年07月24日39分31秒

I'll assume this is correct and accept it as the new answer. Thanks for the update!

1970年01月01日00分03秒

Wanted the objects too, not just their names. This seems to be available in model._meta.fields though, and their names are retrievable with field.name it seems. I just hope this is the most stable way to retrieve this info :)

2019年07月24日39分31秒

not entirely sure. The underscore seems to indicate it's an internal API, would be cool if the Django guys promoted this up to an actually public method call on django.db.models.Model. I'll dig into it and see what I can find

2019年07月24日39分31秒

I guess doing it via the _meta attribute is the only way... Additionally look into _meta.many_to_many for ManyToMany fields!

2019年07月24日39分31秒

lazerscience: I was just going to ask about those! Because I noticed the Django admin has more fields than what I retrieved from _meta.fields. Bryan: Of course :) I review my questions fairly often to accept the best answer... but some of them still don't, and probably never will. Wish I could close em without needing 5 votes.

2019年07月24日39分31秒

It's a good solution but this method includes the reverse relation fields such as a reverse ForeignKey and those are not exactly "fields". Anyone know how to distinguish the actual Fields?

2019年07月24日39分31秒

This should now be the accepted answer. Terse, and to the point.

2019年07月24日39分31秒

Yes this is the answer.

2019年07月24日39分31秒

What about ForeignKey? I have errors like this django.db.models.fields.related.RelatedObjectDoesNotExist: CustomModel has no custom_attribute.

2019年07月24日39分31秒

ForeignKey work fine for me.Although, silently catching all exceptions is an anti-pattern.Much better to catch AttributeError, or at least log that some exception was silently swallowed.

2019年07月24日39分31秒

self._meta.get_all_field_names() has been depreciated and removed.You can use something like for field in self._meta.get_fields() and then yield (field.name, field.value_from_object(self))

2019年07月24日39分31秒

This isn't an answer to the question.

2019年07月24日39分31秒