简体   繁体   English

在运行时获取 Django ForeignKey 字段的 related_name

[英]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_namePet.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.

相关问题 Django 外键相关名称='+' - Django ForeignKey related_name='+' django:自相关 ForeignKey 字段的相关名称不起作用 | 在模板中获取相反方向的自引用 - django: related_name of self related ForeignKey field not working | get opposite direction of self reference in template django外键通过related_name访问 - django foreignkey accessing through related_name django - 在ManyToMany和ForeignKey中使用related_name - django - using of related_name in ManyToMany and in ForeignKey Django:ForeignKey vs related_name - Django: ForeignKey vs related_name 如何通过Django rest获取带有related_name的序列化器中的特定字段 - how to get specific field in serialiser with related_name by Django rest django 获取相关名称字段的“孩子”计数(并在模板中执行此操作?) - django get count of 'children' of related_name field (and do this in template?) 使用继承和ForeignKey时,Django syncdb冲突related_name - Django syncdb conflicting related_name when using inheritance and ForeignKey Django:如何在Abstract Model class中设置ForeignKey related_name? - Django: how to set ForeignKey related_name in Abstract Model class? Django:向后键入提示/related_name/ForeignKey 关系 - Django: typehinting backward / related_name / ForeignKey relationships
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM