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

我与影子孤独终老i 提交于 2019-12-13 15:46:16

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/20772235/django-many-to-may-how-get-row-id-in-related-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!