Django - 多对多的表单字段+额外的“直通”字段

时间:2016-08-11 00:08:46

标签: python django forms many-to-many

我好几天都在寻找解决问题的方法,但我似乎无法找到我想要的东西。我想制作类似购物车的表格,以便在列表中预订一些产品。您将检查所需的产品并填写每个产品的金额。之后可以编辑预订。

我的问题是,预订和产品通过多对多中介模式链接,以获得额外的“数量”字段:

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)

我在管理员中看过一些处理类似问题的帖子,但在这里我需要将它提供给客户端。我曾考虑过使用带有自定义查询集的内联formset,但我无法在不同的类之间建立链接。我总是可以直接从提交的数据中填充我的字段,但是我需要在多个视图中重用该表单,无论如何这对我来说听起来都不是很干。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

首先,您创建一个预约     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 如果事情变得更复杂,请考虑在没有内联表单“快捷方式”的情况下构建自定义表单。