gpt4 book ai didi

django - 有没有办法从 Django 中的模型查询集中获取相关字段的类型?

转载 作者:行者123 更新时间:2023-12-02 15:08:34 24 4
gpt4 key购买 nike

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

让我们考虑示例模型:

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

最佳答案

尝试使用get_field_by_name:

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

来自Django's source code :

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()

关于django - 有没有办法从 Django 中的模型查询集中获取相关字段的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15703635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com