在 Django 中,我有 2 個模型。一種叫做Box,一種叫做Product。一個盒子可以有許多不同的產品,每種產品的數量也不同。例如 box1 可以有 1 個 productA 和 2 個 productB。
我的盒子模型
class Box(models.Model):
boxName = models.CharField(max_length=255, blank = False)
product = models.ManyToManyField(Product)
def __str__(self):
return self.boxName
我的產品型號
class Product(models.Model):
productName = models.CharField(max_length=200)
productDescription = models.TextField(blank=True)
productPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0)
class Meta:
db_table = 'products'
ordering = ['-productName']
def __str__(self):
return self.productName
我如何設定這個模型,讓我在創建盒子物件時選擇產品的數量?
uj5u.com熱心網友回復:
定義一個包含產品 數量的中介模型。
class Box(models.Model):
boxName = models.CharField(max_length=255, blank = False)
product_set = models.ManyToManyField(ProductSet)
def __str__(self):
return self.boxName
class ProductSet(models.Model):
quantity = models.PositiveIntegerField()
product = models.ForeignKey(Product, on_delete = models.PROTECT)
class Product(models.Model):
productName = models.CharField(max_length=200)
productDescription = models.TextField(blank=True)
productPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0)
class Meta:
db_table = 'products'
ordering = ['-productName']
def __str__(self):
return self.productName
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/373810.html
