[英]How to create a table with non-unique id and have it as foreign key in another table?
我在models.py中有以下表格:
class Part(models.Model):
partno = models.CharField(max_length=50, unique=True)
partdesc = models.CharField(max_length=50, default=None, blank=True, null=True)
class Price(models.Model):
part = models.ForeignKey(Part, on_delete=models.CASCADE, null=True)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
qty = models.IntegerField(default=1)
price = models.DecimalField(max_digits=9, decimal_places=2)
currency = models.ForeignKey(Currency, on_delete=models.CASCADE)
datestart = models.DateTimeField(auto_now_add=True, blank=False, null=False)
class Meta:
unique_together = (('supplier', 'part'),)
這是正常工作。 問題是我有很多零件號可以替代它們。 例如,零件1001-01、1001-02、1001-03都是相同的零件。 不過,我的Part表中都有它們。
我需要在另一張表中將它們匹配,因此不需要分別輸入它們的價格。 必須有一個代表所有這三個項目的唯一密鑰。
問題:如何設置“零件號匹配表”,並在價格表中具有該表的外鍵?
(Rest是可選的,目前為止我的觀點/問題可能有幫助)
1:我試圖像這樣設置表格:
class PartMatch(models.Model):
id = models.IntegerField(primary_key=True, unique=False, null=False, db_index=True)
part = models.ForeignKey(Part, unique=False, on_delete=models.CASCADE)
遷移時沒有出現錯誤,但是當我嘗試對PK使用相同的ID時,它不允許我這樣做。
2:我獨自留下了pk,並嘗試設置另一個字段以匹配各個部分:
class PartMatch(models.Model):
part = models.ForeignKey(Part, on_delete=models.CASCADE)
partmatchid = models.IntegerField(null=True, unique=False, db_index=True)
我在遷移時沒有任何錯誤,但是當我嘗試使用partmatchid
作為Price
表中的外鍵時,如下所示:
partmatch = models.ForeignKey(PartMatch, to_field="partmatchid",
db_column="partmatchid",
on_delete=models.CASCADE)
我收到一個錯誤消息,說遷移時foreign key must be unique
。
好吧,在這種情況下,我無法解決問題。 我不知道你們如何處理?
您的Part
模型可以具有PartMatch
的外鍵, PartMatch
不行。
您的模型可以是Part *<-->1 PartMatch
和PartMatch 1<-->1 Price
例如:
class Price(models.Model):
price = models.DecimalField(max_digits=9, decimal_places=2)
class PartMatch(models.Model):
price = models.OneToOneField(Price, primary_key=True)
class Part(models.Model):
partno = models.CharField(max_length=50, unique=True)
partMatch = models.ForeignKey(PartMatch)
如果要以某個價格獲得所有零件, some_price.partmatch.part_set.all()
將完成此工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.