[英]Get related_name of Django ForeignKey field at runtime
Let's say I have the following Django models:假设我有以下 Django 模型:
class Person(models.Model):
name = models.CharField(max_length=50)
class Pet(models.Model):
name = models.CharField(max_length=50)
person = models.ForeignKey(Person, related_name='pets', on_delete=models.CASCADE)
I need to get the string value of related_name
for Pet.person
at runtime.我需要得到的字符串值related_name
为Pet.person
在运行时。 I can get the related_query_name
, which is "pet"
but that's slightly different than the related_name
, which is "pets"
:我可以得到related_query_name
,即"pet"
但与related_name
略有不同,即"pets"
:
print(Pet._meta.get_field("person").related_query_name())
# pet
Looks like the related name is on the Person
class, but I'm not sure how to prove it's tied to Pet.person
.看起来相关名称在Person
类上,但我不确定如何证明它与Pet.person
相关Pet.person
。
print("pets" in [f.name for f in Person._meta.get_fields()])
# True
Is there anyway to do this?有没有办法做到这一点?
Try this,尝试这个,
related_name = Pet._meta.get_field('person').remote_field.get_accessor_name()
related_query_name = Pet._meta.get_field('person').related_query_name()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.