[英]Django : Foreign Key to a choice field model
我對 Python / Django 比較陌生。
我正在嘗試在食品與其所屬的類別(名稱)之間建立關系:
class Category(models.Model):
options=(
('vegetable','vegetable'),
('fruit','fruit'),
('carbs','carbs'),
('fish','fish'),
('meat', 'meat'),
('sweet', 'sweet'),
('dairy', 'dairy'),
)
name=models.CharField(max_length=10,choices=options,unique=True)
def __str__(self):
return self.name
class Fooditem(models.Model):
name = models.CharField(max_length=50)
category = models.ForeignKey(Category,on_delete=models.CASCADE)
上面的代碼在運行 migrate 時拋出錯誤: ValueError: invalid literal for int() with base 10: 'vegetable'
我在數據庫中創建了一些項目,是這個原因嗎?
解決此問題的最佳方法是什么? 謝謝你,D
它會修復它,但你可能會得到一些意想不到的結果。
category = models.ForeignKey(Category,on_delete=models.CASCADE)
將是一個指向另一個 model 的 id。
您可以通過將 name 更改為以下內容來將其設為主鍵:
name=models.CharField(max_length=10,choices=options,unique=True,primary_key=True)
此外,更仔細地查看https://docs.djangoproject.com/en/3.1/ref/models/fields/#choices可能會幫助您在未來做出選擇。 它將編程更容易定義為成本並遵循他們的語法
我真的建議你這樣做。 如果有不清楚的地方請告訴我
class Category(models.TextChoices):
vegetable='vegetable'
fruit='fruit'
carbs='carbs'
fish='fish'
meat='meat'
sweet='sweet'
dairy='dairy'
class Fooditem(models.Model):
name = models.CharField(max_length=50)
category = models.CharField(max_length=20, choices=Category.choices)```
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.