15👍
You can use get_field_by_name on the models _meta object:
from django.db.models import ForeignKey
def get_fk_model(model, fieldname):
"""Returns None if not foreignkey, otherswise the relevant model"""
field_object, model, direct, m2m = model._meta.get_field_by_name(fieldname)
if not m2m and direct and isinstance(field_object, ForeignKey):
return field_object.rel.to
return None
Assuming you had a model class MyModel you would use this thus:
fk_model = get_fk_model(MyModel, 'fieldname')
6👍
Simple one liner to find all the relations to other models
that exist in a model
:
In [8]: relations = [f for f in Model._meta.get_fields() if (f.many_to_one or f.one_to_one) and f.auto_created]
Above will give a list
of all the models
with their relations
.
Example:
In [9]: relations
Out[9]:
[<ManyToOneRel: app1.model1>,
<ManyToOneRel: app2.model1>,
<OneToOneRel: app1.model2>,
<OneToOneRel: app3.model5>,
<OneToOneRel: app5.model1>]
- Pycharm Django Debugging is really slow
- Django testing: Got an error creating the test database: database "database_name" already exists
- What is query.clone(), queryset.clone() for in django?
1👍
I encountered the same use case, and the accepted answer did not work for me directly. I am using Django 1.2 if it’s relevant. Instead, I used the get_field_by_name
method as follows.
def get_foreign_keys(self):
foreign_keys = []
for field in self._meta.fields:
if isinstance(self._meta.get_field_by_name(field.name)[0], models.ForeignKey):
foreign_keys.append(field.name)
if not foreign_keys:
return None
return foreign_keys
This is a method define inside a class. For my case, what I needed are the names of the ForeignKey fields. Cheers!
- Django annotate and count: how to filter the ones to include in count
- Making Twitter, Tastypie, Django, XAuth and iOS work to Build Django-based Access Permissions
- Django sub-applications & module structure
1👍
You can use the property is_relation of a model’s Field to determine whether it’s a ForeignKey, ManyToManyField, or OneToOneField. This is set to True in all these classes. All other field types are False.
You can obtain the field class by calling Model._meta.get_field()
. Example:
field = table_obj._meta.get_field(column)
if field.is_relation:
...
0👍
Explore the “ModelChoiceField” fields. Can they solve your problem putting foreign keys into forms for you; rather than doing that yourself.
http://docs.djangoproject.com/en/1.1/ref/forms/fields/#fields-which-handle-relationships
record = forms.ModelChoiceField(queryset=table_obj.objects.all())
- Paypal monthly subscription plan settings for first day of the month and making monthly recurring payment – django python
- Django, REST and Angular Routes