Codeboy.ru
Codeboy.ru

Reputation: 81

Django many-to-may : how get row id in related table

I have 2 simple models for example

class First(m.Model):
    target_field = m.CharField()
class Second(m.Model):
    link_field = m.ManyToManyField(First)

Related linking table look like this: id | second_id | first_id

How can i get ID? Not second_id or first_id - exactly row ID. I cant find Django methods for it, and wrote it my self. Thanks for help.

UPD. For frontend API i need cross ID for related objects.

q_second = Second.objects.select_related().all()
for i in q_second.link_field.all()
    print i.pk

this print ID in First table its ok, but i need row id in related second_link_field table

Upvotes: 2

Views: 1942

Answers (2)

NikolaS
NikolaS

Reputation: 111

May be you need this:

seconds = Second.objects.all()
for second in seconds:
    for i in Second.link_field.through.objects.filter(link_field=second):
        print i.id

through object is a usual django model corresponding intermediate table of many-to-many field, you can query it to fetch ids of entries

Upvotes: 4

greg
greg

Reputation: 1416

You can use through https://docs.djangoproject.com/en/1.6/ref/models/fields/#django.db.models.ManyToManyField.through and overwrite this model manually. So you can get second_id or first_id just using ORM.

Upvotes: 1

Related Questions