Django多对五:如何在相关表中获取行ID [英] Django many-to-may : how get row id in related table
问题描述
例如,我有2个简单的模型
I have 2 simple models for example
class First(m.Model):
target_field = m.CharField()
class Second(m.Model):
link_field = m.ManyToManyField(First)
相关的链接表如下所示: id | second_id | first_id
Related linking table look like this: id | second_id | first_id
我如何获得身份证?不是second_id或first_id-确切是行ID. 我找不到它的Django方法,而是自己写的. 感谢您的帮助.
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. 对于前端API,我需要相关对象的交叉ID.
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
第一个表中的此打印ID可以,但是我需要相关的second_link_field表中的行ID
this print ID in First table its ok, but i need row id in related second_link_field table
推荐答案
也许您需要这个:
seconds = Second.objects.all()
for second in seconds:
for i in Second.link_field.through.objects.filter(link_field=second):
print i.id
through
对象是通常的django模型,对应于多对多字段的中间表,您可以查询它以获取条目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
这篇关于Django多对五:如何在相关表中获取行ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!