Django - ManyToMany表拉错信息

时间:2016-07-26 13:05:42

标签: python mysql django foreign-keys mariadb

我正在尝试为这两个表之间的多对多关系创建一个链接表。第三个表将包含第一个表中的cand_id和来自第二个表的p_id。这是我在候选人中的代码和模型中的P_user classes以及MariaDB中的表。当我在Candidate模型中使用ManyToManyField选项时,它会不断提取用户的名字而不是p_id

第一个模型:

class P_user(models.Model):
    ''' Proxy database model to extend Django User with profile data.'''

    user       = models.ForeignKey(User)
    p_id = models.CharField(primary_key = True)
    phone      = models.CharField(max_length = 20, 
                                  default    = '',
                                      blank      = True)
    password = models.CharField(max_length = 30,
                          default    = '',
                                          blank      = True)
        confirm_password = models.CharField(max_length = 30,
                          default    = '',
                                          blank      = True)
        roles = models.CharField(max_length = 30,
                          default    = '',
                          blank      = True)

第二种模式:

class Candidate(models.Model)

    ....
    associated_hm = models.ManyToManyField(P_user,
                          blank      = True)
    ....

数据库表示:

MariaDB [mantis]> describe prog_port_candidate;

+------------------------+--------------+------+-----+---------+----------------+

| Field                  | Type         | Null | Key | Default | Extra          |

+------------------------+--------------+------+-----+---------+----------------+

| cand_id                | int(11)      | NO   | PRI | NULL    | auto_increment |

| first_name             | varchar(20)  | NO   |     | NULL    |                |

| last_name              | varchar(20)  | NO   |     | NULL    |                |


+------------------------+--------------+------+-----+---------+----------------+

下一个:

MariaDB [mantis]> describe prog_port_p_user;
+------------------+-------------+------+-----+---------+-------+

| Field            | Type        | Null | Key | Default | Extra |

+------------------+-------------+------+-----+---------+-------+

| p_id             | varchar(8)  | NO   | PRI | NULL    |       |

| phone            | varchar(20) | NO   |     | NULL    |       |

| password         | varchar(30) | NO   |     | NULL    |       |

| confirm_password | varchar(30) | NO   |     | NULL    |       |

| roles            | varchar(30) | NO   |     | NULL    |       |

| user_id          | int(11)     | NO   | MUL | NULL    |       |

+------------------+-------------+------+-----+---------+-------+

1 个答案:

答案 0 :(得分:0)

这可能是一个很长的问题,因为你的问题没有明确错误输出的上下文,但是如果你只是引用你的模型.associated_hm,你会看到对associated_hm对象的引用。

要获取p_id,您需要在查询中明确引用yourmodel.associated_hm.p_id