我的Postgres数据库中有2个表。一个包含来自世界不同地区的多个州,另一个包含这些州中的邮政编码。
它们是一个城市中的多个邮政编码。但是邮政编码仅链接到一个城市。
这是我的2张桌子的示例:
状态:
+----+------------+-----------+-----------------------+
| pk | state | city | city_id |
+----+------------+-----------+-----------------------+
| 1 | Montreal | Quebec | 123 |
+----+------------+-----------+-----------------------+
| 2 | Laval | Quebec | 123 |
+----+------------+-----------+-----------------------+
| 3 | Ottawa | Ontario | 837 |
+----+------------+-----------+-----------------------+
邮政编码:
+----+------------+-----------+-----------------------+
| pk |Postal Code | city | city_id |
+----+------------+-----------+-----------------------+
| 1 | H1H1H1 | Quebec | 123 |
+----+------------+-----------+-----------------------+
| 2 | H4P2T5 | Quebec | 123 |
+----+------------+-----------+-----------------------+
| 3 | G1G2G2 | Ontario | 837 |
+----+------------+-----------+-----------------------+
我正在使用django autocomplete-light进行输入,现在我想转发状态以使用city_id字段过滤邮政编码。
我遇到的问题是Django错误告诉我:
'stateModel.city_id' must set unique=True because it is referenced by a foreign key.
当我尝试使用非唯一的外键时,因为同一城市可能在不同的州使用。当我尝试使用ManyToMany
时,我得到了这个错误。ERREUR: la relation « postalCodeModel_city_id » n'existe pas
LINE 1: ...COUNT(*) AS "__count" FROM "postalCodeModel" INNER JOIN "postalCodeModel...
当我尝试创建一对多字段或默认情况下(如果我选择ManyToManyField选项发送pk时)。
是否可以通过州模型从城市中过滤邮政编码?我是否需要创建一个City表,然后在此新表中创建一个带有Trought选项的ManyToManyField?
class stateModel(models.Model):
idunique = models.IntegerField(unique=True, blank=True, null=True)
state = models.TextField(blank=True, null=True)
city = models.TextField(blank=True, null=True)
city_id = models.TextField(blank=True, null=True)
def __str__(self):
return self.state
class Meta:
managed = False
db_table = 'stateDB'
class codePostalModel(models.Model):
cp_id = models.IntegerField(blank=True, null=True)
cp = models.TextField(blank=True, null=True)
#city_id_cp = models.TextField(blank=True, null=True)
city_id_cp = models.ForeignKey(stateModel, to_field='city_id', blank=True, null=True, on_delete=models.CASCADE)
#city_id_cp = models.ManyToManyField(stateModel)
def __str__(self):
return self.cp
class Meta:
managed = False
db_table = 'postalCodeDB'