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?
ForeignKeys are
ReverseSingleRelatedObjectDescriptor
objects. So that's what you are really working with. You'll get that if you runtype(SubCategory.category)
. From here you can use two ways to get the actual Class/Model referred to.If you don't know the attribute name until run-time, then use
getattr(SubCategory, attributeNameVariable)
to get yourReverseSingleRelatedObjectDescriptor
object for that ForeignKey field.For Django>=2.0
To get the model name use the
__name__
class property.also for django > = 2.0
Try:
EDIT: