python - Django - 多对多表单字段+额外的 "through"字段

标签 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)

我在管理员中看到一些处理类似问题的帖子,但在这里我需要将其提供给客户。我考虑过使用带有自定义查询集的内联表单集,但我无法设法在不同类之间建立链接。我总是可以直接从提交的数据中填充我的字段,但我需要在多个 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 如果事情变得更复杂,请考虑构建一个没有内联表单“快捷方式”的自定义表单。

关于python - Django - 多对多表单字段+额外的 "through"字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38885403/

相关文章:

python - 如何在 python session 中获取 duckdb 可见的类表对象列表?

python - SciPy zeta 函数返回非常大的值

python - 自定义 django-revproxy 权限

html - 在 div 中垂直居中表单

spring - Thymeleaf:按字段验证错误

html - 长 HTML 输入表单的最佳设计

python - 将 FastAPI 服务器与 Celery Workers 服务器分开 - 目录结构

python - 带有数据的 Scipy 中的微分进化

python - 无法在 View 中设置 Django 表单的字段值

django - 如何在您具有只读访问权限的现有数据库上实现django admin?