将(postgresql)SQL移植到django模型类中

时间:2017-05-23 21:04:41

标签: django postgresql

我正在移植数据库模式(手动),从(postgresql)SQL移植到django(1.10)模型。

这是我的SQL:

CREATE TABLE ref_continent  (
                                    id                  SERIAL PRIMARY KEY,
                                    name                VARCHAR(64)
                            );
CREATE UNIQUE INDEX idxu_continent_nm ON ref_continent (name);



CREATE TABLE ref_geographic_region  (
                                     id                  SERIAL PRIMARY KEY,
                                     continent_id        INTEGER REFERENCES ref_continent(id) ON DELETE RESTRICT ON UPDATE CASCADE,
                                     name                VARCHAR(256)
                                     );
CREATE UNIQUE INDEX idxu_geogreg_nm ON ref_geographic_region (name);

我特别感兴趣的是如何创建 UNIQUE INDEX 以及如何将 FK 链接到 PKey ,因为(AFAIK), django在幕后创建主键 id

1 个答案:

答案 0 :(得分:0)

根据docs

  

请注意,当unique为True时,您不需要指定db_index,   因为unique意味着创建索引。

好吧,当您将模型链接为外键时,它会链接到默认FK(默认情况下为#id)。

  

models.ForeignKey(' app_name.ref_continent',)

还有另一个用于修复这些东西的类META。您几乎不必指定将FK链接到其他表的PK,这完全由Django完成。有一个source code

 models.py

def ucs(G, v):
    visited = set()                  # set of visited nodes
    q = queue.PriorityQueue()        # paths are tuples with cumulative cost
    q.put((0, [v]))                  # add the starting node, zero cost   

    while not q.empty():             # while the queue is nonempty
        current_path_priority, current_path = q.get()  # get top item
        current_node = current_path[-1]    # current_node is the node at the end  
        visited.add(current_node)          # mark it as visited

        if current_node.is_goal:           # if the current node is a goal
            return current_path            # return it

        else:
            for edge in current_node.out_edges: # otherwise, for each neighbour
                child = edge.to()             # (avoid calling .to() in future)

                if child not in visited:                # if it is not visited 
                    new_cost = current_path_priority + edge.weight  
                    q.put((new_cost, current_path + [child]))