几天来我一直在寻找解决问题的方法,但似乎找不到我想要的东西。我想制作类似购物车的表格来预订列表中的一些产品。您将检查您需要的产品并填写每个产品的数量。之后可以编辑预订。
我的问题是,预订和产品通过多对多中介模型链接,以具有额外的“数量”字段:
class Reservation(models.Model):
# some fields...
products = models.ManyToManyField(Product, through='ProductReservation')
class Product(models.Model):
# some fields...
class ProductReservation(models.Model):
quantity = models.IntegerField()
reservation = models.ForeignKey(Reservation)
product = models.ForeignKey(Product)
我在管理员中看到一些处理类似问题的帖子,但在这里我需要将其提供给客户。我考虑过使用带有自定义查询集的内联表单集,但我无法设法在不同类之间建立链接。我总是可以直接从提交的数据中填充我的字段,但我需要在多个 View 中重复使用该表单,无论如何这对我来说听起来不是很枯燥。
感谢您的帮助!
请您参考如下方法:
所以首先你创建一个预订 reservation = Reservation.objects.create(some_field=some_value)
然后你创建一个产品 product = Product.objects.create(some_field=some_value)
最后,您可以使用 ProductReservation 创建两者之间的链接 ProductReservation.create(quantity=100, reservation=reservation, product=product)
您的表单可以建立在 ProductReservation 模型之上。 这里提到如何:Accessing Many to Many "through" relation fields in Formsets 如果事情变得更复杂,请考虑构建一个没有内联表单“快捷方式”的自定义表单。
