Max Chandler
Max Chandler

Reputation: 513

How to detect if a Model property is a foreign key relation? (And retreive all FK Model objects)

I'm trying to create a table that propagates dynamically with django objects, where each row is a django model object. If the object property is a foreign key, the goal is to display a drop-down list of all the possible FK options. To do this, I'll need to detect if the object field is an FK and then retrieve all FK objects.

There are two components to this:

The idea in pseudocode would be:

for field in object.fields:
  if field is FK:
    return field.objects.all()
  else:
    return field

I know that I can test for a ForwardManyToOneDescriptor relation (below), but is there a more compact general way to test for a FK relationship?

isintance(Foo.bar, db.models.fields.related_descriptors.ForwardManyToOneDescriptor):

Is there any way of getting all of the model objects of the FK, either by the model class or an instance of the class? Foo.bar.all() or Foo.objects.first().bar.all()

Upvotes: 1

Views: 758

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

Instead of iterating over the object fields, you can access the _meta object, and iterate over the fields, like:

from django.db import model

[f for f in t._meta.get_fields() if isinstance(f, models.ForeignKey)]

You can obtain the model that is referenced with:

[f.related_model for f in t._meta.get_fields() if isinstance(f, models.ForeignKey)]

You thus can obtain querysets with all objects with:

[f.related_model.objects.all() for f in t._meta.get_fields() if isinstance(f, models.ForeignKey)]

Upvotes: 1

Related Questions