31👍
✅
Try:
subcategory = SubCategory.objects.get(pk=given_pk)
subcategory.category
EDIT:
subcategory._meta.get_field('category').rel.to
30👍
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'
- [Django]-A Better Django Admin ManyToMany Field Widget
- [Django]-How to make Django's devserver public ? Is it generally possible?
- [Django]-Django 1.7 upgrade error: AppRegistryNotReady: Apps aren't loaded yet
13👍
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.
- [Django]-Django: show/log ORM sql calls from python shell
- [Django]-ImageField overwrite image file with same name
- [Django]-How to upgrade django?
8👍
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'
- [Django]-Django rest framework: query parameters in detail_route
- [Django]-How to get username from Django Rest Framework JWT token
- [Django]-How to register users in Django REST framework?
Source:stackexchange.com