Ed.
Ed.

Reputation: 4597

Programmatically identify django foreignkey links but omit through tables

I asked a question earlier to programmatically identity foreignkey links..

I found that the below code pulls all the one-to-many links:

yourModel._meta.get_all_related_objects()

The only problem I'm finding now though is that it also includes interemdiary tables that are going to many-to-many links. So if I have the below model,

class Model_one(models.Model):
    name = models.CharField("Name", max_length=30)
    people = models.ManyToManyField('Model_two', blank=True, through='Association')

Instead of returning nothing, the code returns Association. Is there a way to either specify "real" one-to-many links or otherwise omit through tables? Even if I have to delete it manually from the returned yourModel._meta.get_all_related_objects()?

Another way to ask this: How can I identify/isolate a link that is actually a "through" table?

Upvotes: 0

Views: 252

Answers (2)

Ed.
Ed.

Reputation: 4597

Found a question that led me in the right direction:

m2m_links =MyModel._meta.local_many_to_many
for r in m2m_links:
    if not r.rel.through._meta.auto_created:
        print r.rel.through._meta.object_name

This will give the name of the "through" tables

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239430

You can test each item to see if it's in _meta.get_all_related_many_to_many_objects():

related_m2ms = MyModel._meta.get_all_related_many_to_many_objects()
for related in MyModel._meta.get_all_related_objects():
     if related not in related_m2ms:
         # Do something here with only one-to-many relationships

Upvotes: 1

Related Questions