如何使用直通模型实现ManyToMany表单并一次记录多个关系

我有一个简单的订单和产品模型。它们具有M2M关系,因此一个产品可以有多个订单,一个订单可以有多个产品。

我需要一个表格供用户收集以下信息:

  • 要订购的产品列表以及其中每种产品的单位
  • 订单创建日期
  • 下订单的用户

据我了解,我需要一个贯穿模型来记录每个产品的单位,我对此表示满意,但是我不知道如何在Forms.py和Views.py中实现它,在html中。

如何在每个“产品” MultipleChoice字段旁边显示一个“单位”字段?

我已经在管理站点中尝试了直通模型的“添加表单”,但是它只允许我一个一个地添加关系。谷歌搜索后,我设法获得了这样的表格,但是再说一次,这不是我想要的表格。

在一个神奇的场景中,我将使用带有django-autocomplete的TextWidgets的多个表单字段在其中搜索产品(每个产品类别一个字段,使查找内容更加容易),然后将所有这些字段合并以创建Order模型的实例。 当然,只要我可以用相同的形式记录多个产品,并且每个字段对应一个单位字段,就足够了。

class Product(models.Model):
    nombre = models.CharField(max_length=50,help_text=_('Nombre del producto.'))
    referencia = models.CharField(max_length=20,help_text = _('Referencia del producto.'))
    formato = models.CharField(max_length=40,help_text=_('Ej.: "Caja de 100","Bolsa de 1000",etc.'))
    marca = models.CharField(max_length=20)

    CATEGORIES = (
        ('a',_('Pipetas serológicas')),('b',_('Puntas micropipeta')),('c',_('Tubos y criotubos')),('d',_('Frascos de cultivo')),('e',_('Guantes')),('f',_('Cortantes')),('g',_('Jeringuillas')),('h',_('Placas y microplacas')),('i',_('Consumible genérico')),)

    category = models.CharField(
        max_length=1,choices=CATEGORIAS,blank=False,help_text=_('Categoría del producto.'),)

    class Meta:
        verbose_name = _("Producto fungible")
        verbose_name_plural = _("Productos fungible")


class Order(models.Model):
    codigo = models.CharField(max_length=20,blank=True)
    producto = models.ManyToManyField(Product,through='Units')
    autor = models.ForeignKey(User,on_delete=models.SET_NULL,blank = True,null = True)
    fecha = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = _("Pedido fungible")
        verbose_name_plural = _("Pedidos de fungible")


class Units(models.Model):
    producto = models.ForeignKey(Product,null = True)
    pedido = models.ForeignKey(Order,null = True)
    unidades = models.IntegerField(default=1)

    class Meta:
        verbose_name = _("Unidad fungible")
        verbose_name_plural = _("Unidades fungibles")
zjwmomo 回答:如何使用直通模型实现ManyToMany表单并一次记录多个关系

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3157612.html

大家都在问