如何在Django的多对多关系中关联数量
How to associate quantity amount in Django's many to many relationship
在 Django 中我有 2 个模型。一种叫做 Box,一种叫做 Product。一个盒子可以有许多不同的产品,并且每种产品的数量不同。例如 box1 可以有 1 个产品 A 和 2 个产品 B。
我的盒子模型
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
我如何设置这个模型允许我在创建盒子对象时 select 数量的产品?
定义一个包含产品 + 数量的中介模型。
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
在 Django 中我有 2 个模型。一种叫做 Box,一种叫做 Product。一个盒子可以有许多不同的产品,并且每种产品的数量不同。例如 box1 可以有 1 个产品 A 和 2 个产品 B。
我的盒子模型
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
我如何设置这个模型允许我在创建盒子对象时 select 数量的产品?
定义一个包含产品 + 数量的中介模型。
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