Django- Get Foreign Key Model
34,581
Solution 1
Try:
subcategory = SubCategory.objects.get(pk=given_pk)
subcategory.category
EDIT:
subcategory._meta.get_field('category').rel.to
Solution 2
For Django>=2.0
>>> SubCategory._meta.get_field('category').remote_field.model
>>> 'my_app.models.Category'
To get the model name use the __name__
class property.
>>> SubCategory._meta.get_field('category').remote_field.model.__name__
>>> 'Category'
Solution 3
ForeignKeys are ReverseSingleRelatedObjectDescriptor
objects. So that's what you are really working with. You'll get that if you run type(SubCategory.category)
. From here you can use two ways to get the actual Class/Model referred to.
SubCategory.category.field.rel.to # <class 'path.to.Model'>
SubCategory.category.field.rel.to.__name__ # 'Category'
# or these will do the same thing
SubCategory._meta.get_field('category').rel.to
SubCategory._meta.get_field('category').rel.to.__name__
If you don't know the attribute name until run-time, then use getattr(SubCategory, attributeNameVariable)
to get your ReverseSingleRelatedObjectDescriptor
object for that ForeignKey field.
Solution 4
also for django > = 2.0
>>> SubCategory._meta.get_field('category').related_model
>>> <class 'my_app.models.Category'>
>>> SubCategory._meta.get_field('category').related_model._meta.model_name
>>> 'category'
Author by
Admin
Updated on September 13, 2020Comments
-
Admin over 3 years
How can I Get A Foreign Key Model Type?
For Example:
class Category(models.Model): name = models.CharField(max_length = 100) class SubCategory(models.Model): category = models.ForeignKey(Category) title = models.CharField(max_length = 100)
I Want To Get category Model In SubCategory.
How Can I Do It?
-
Tomek Paczkowski over 12 yearsOh... Then is very simple: always Category.
-
Admin over 12 yearsKidding Me? It's A Sample. I Want The To Get The Foreign Key Dynamically!
-
Admin over 12 yearsYou Say True. Thank You Very Very Much :-)
-
AnonymousUser over 2 yearsHow to do
category = Category.objects.get(pk=given_pk)
category.subcategory
? I wanna do it this way, but it's not working.