我可以从模型查询集中获取相关字段的类型吗?
让我们考虑示例模型:
class Semester(models.Model):
active = models.BooleanField(default=False, verbose_name="Active")
class Subject(models.Model):
name = models.CharField(max_length=100, verbose_name="Name")
semester = models.ForeignKey(Semester, verbose_name="Semester")
如果我在变量和查询集中有一些字段名称,我可以这样做:
querySet = Subject.objects.all()
some_field_name = 'name'
field_type = querySet.model._meta.get_field(some_field_name).get_internal_type()
有没有办法获得相关的字段类型,例如:
querySet = Subject.objects.all()
some_field_name = 'semester__active'
field_type = ?
答案 0 :(得分:2)
尝试使用get_field_by_name
:
field_type = querySet.model._meta.get_field_by_name(some_field_name).get_internal_type()
def get_field_by_name(self, name):
"""
Returns the (field_object, model, direct, m2m), where field_object is
the Field instance for the given name, model is the model containing
this field (None for local fields), direct is True if the field exists
on this model, and m2m is True for many-to-many relations. When
'direct' is False, 'field_object' is the corresponding RelatedObject
for this field (since the field doesn't have an instance associated
with it).
Uses a cache internally, so after the first access, this is very fast.
"""
还可以尝试:
field = querySet.model._meta.get_field_by_name("semester")
field_type = field[0].rel.to._meta.get_field_by_name("active").get_internal_type()
答案 1 :(得分:1)
感谢您的帮助!
我在this answer的帮助下找到了解决方案:
main, related = some_field_name.split("__")
field_type = querySet.model._meta.get_field(main).rel.to._meta.get_field(related).get_internal_type()