检查外键是否彼此相等
我有一个 [(3,2),(2,3)]
形式的外键元组列表。我想将项目插入模型内的 ManyToMany 表中:
class Place(models.Model):
data=models.IntegerField()
connected_to=models.ManyToManyField('self')
class PlaceMeta(models.Model):
place=models.ForeignKey("places.Place")
并且我插入列表(连接):
places=Place.objects.all()
for conn_1, conn_2 in connections:
for place in places:
if place.data == conn_1 and conn_1 != conn_2:
place.connected_to.add(conn_1, conn_2)
elif place.data == conn_2 and conn_1 != conn_2:
fixture.connected_to.add(conn_2, conn_1)
当我打印列表时,它会打印 [(3L, 2L),(2L, 3L)]< /code> (例如),但在我插入后,表显示 (2,2)、(3,2)、(2,3) 和 (3,3) 已插入。
我在代码中的多个点尝试检查元组 (a,a) 是否存在,并且当我在插入之前打印时,它显示没有这样的元组。那么,如何避免插入这样的元组,因为在插入之前它们甚至不存在于列表中?
I have a list of tuples of foreign keys of the form [(3,2),(2,3)]
. And I want to insert the items into a ManyToMany table within a model:
class Place(models.Model):
data=models.IntegerField()
connected_to=models.ManyToManyField('self')
class PlaceMeta(models.Model):
place=models.ForeignKey("places.Place")
and I am inserting the list (connections) with:
places=Place.objects.all()
for conn_1, conn_2 in connections:
for place in places:
if place.data == conn_1 and conn_1 != conn_2:
place.connected_to.add(conn_1, conn_2)
elif place.data == conn_2 and conn_1 != conn_2:
fixture.connected_to.add(conn_2, conn_1)
When I print the list it prints [(3L, 2L),(2L, 3L)]
(for example) but after I insert the table shows that (2,2),(3,2),(2,3),and (3,3) have been inserted.
I've tried at multiple points in the code to check for if a tuple (a,a) exists and when I print prior to inserting it shows no such tuple. So how do I avoid inserting such tuples seeing as they don't even appear to exist in the list before I insert?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在调用
add()
时有一个参数过多。它应该如下所示:并且您不需要遍历所有地点,而是使用
objects.get
或objects.filter
取决于data
code> 是否唯一。例如,如果它是唯一的,请使用:(并且可能将
unique=True
属性添加到data
字段)You have one parameter too much in you call to
add()
. It should look like this:And you don't need to iterate through all the Places, instead use
objects.get
orobjects.filter
depending ifdata
is unique or not. For example, if it is unique, use:(and probably add the
unique=True
attribute to thedata
field)