2013-03-11 40 views
1

我想使用d3js来显示我的Django网站用户之间的连接。 我正在重复使用代码the force directed graph示例,要求每个节点都有两个属性(ID和名称)。我已经为user_profiles_table中的每个用户创建了一个节点,并基于connections_table中的每一行在已创建的节点之间添加了一条边。这是行不通的;当我开始使用connection_table时,networkx会创建新节点。Django/NetworkX消除重复节点

nodeindex=0 
for user_profile in UserProfile.objects.all(): 
    sourcetostring=user_profile.full_name3() 
    G.add_node(nodeindex, name=sourcetostring) 
    nodeindex = nodeindex +1 

for user_connection in Connection.objects.all(): 
    target_tostring=user_connection.target() 
    source_tostring=user_connection.source() 
    G.add_edge(sourcetostring, target_tostring, value=1) 

data = json_graph.node_link_data(G) 

结果:

{'directed': False, 
'graph': [], 
'links': [{'source': 6, 'target': 7, 'value': 1}, 
    {'source': 7, 'target': 8, 'value': 1}, 
    {'source': 7, 'target': 9, 'value': 1}, 
    {'source': 7, 'target': 10, 'value': 1}, 
    {'source': 7, 'target': 7, 'value': 1}], 
'multigraph': False, 
'nodes': [{'id': 0, 'name': u'raymondkalonji'}, 
    {'id': 1, 'name': u'raykaeng'}, 
    {'id': 2, 'name': u'raymondkalonji2'}, 
    {'id': 3, 'name': u'tester1cet'}, 
    {'id': 4, 'name': u'tester2cet'}, 
    {'id': 5, 'name': u'tester3cet'}, 
    {'id': u'tester2cet'}, 
    {'id': u'tester3cet'}, 
    {'id': u'tester1cet'}, 
    {'id': u'raykaeng'}, 
    {'id': u'raymondkalonji2'}]} 

我怎样才能消除重复的节点?

回答

3

您可能会重复节点,因为您的user_connection.target()user_connection.source()函数会返回节点名称,而不是其ID。当您拨打add_edge时,如果图中不存在端点,则会创建端点,这就解释了为什么会出现重复。

下面的代码应该可以工作。

for user_profile in UserProfile.objects.all(): 
    source = user_profile.full_name3() 
    G.add_node(source, name=source) 

for user_connection in Connection.objects.all(): 
    target = user_connection.target() 
    source = user_connection.source() 
    G.add_edge(source, target, value=1) 

data = json_graph.node_link_data(G) 

还要注意的是,如果你想有一个正确格式的JSON字符串你应该转储data对象为JSON。你可以这样做,如下所示。

import json 
json.dumps(data)     # get the string representation 
json.dump(data, 'somefile.json') # write to file