开发者

Checking if ForeignKeys are equal to one another

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?


You have one parameter too much in you call to add(). It should look like this:

if place.data == conn_1 and conn_1 != conn_2:
    # place is the Place instance described by conn_1.
    # Let's connect it to conn_2!
    place.connected_to.add(conn_2)

And you don't need to iterate through all the Places, instead use objects.get or objects.filter depending if data is unique or not. For example, if it is unique, use:

for source, target in connections:
   Place.objects.get(data=source).connected_to.add(Place.objects.get(data=target))

(and probably add the unique=True attribute to the data field)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜