4

我可以从模型查询集中获取相关字段的类型吗?

让我们考虑示例模型:

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 = ?
4

2 回答 2

2

尝试使用get_field_by_name

field_type = querySet.model._meta.get_field_by_name(some_field_name).get_internal_type()

来自Django 的源代码

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()
于 2013-03-29T13:45:40.313 回答
1

谢谢你的帮助!

我在这个答案的帮助下找到了解决方案:

main, related = some_field_name.split("__")
field_type = querySet.model._meta.get_field(main).rel.to._meta.get_field(related).get_internal_type()
于 2013-03-29T14:27:54.660 回答