简体   繁体   English

通过 model 对象迭代 django m2m

[英]Iterate over django m2m through model objects

I have the following ManyToMany relationship in my project:我的项目中有以下多对多关系:

class Borrador(models.Model):

    nombre = models.CharField(
        max_length=40,
        help_text=_('Nombre para identificar al borrador.')
    )
    productos = models.ManyToManyField(
        Producto,
        through=Articulo,
    )

class Articulo(models.Model):

    producto = models.ForeignKey(
        Producto,
        on_delete=models.SET_NULL,
        null=True
    )
    borrador = models.ForeignKey(
        'Borrador',
        on_delete=models.SET_NULL,
        null=True
    )
    unidades = models.IntegerField(
        default=1
    )

class Producto(models.Model):

    nombre_amistoso = models.CharField(
        max_length=40,
        help_text=_('Nombre corto para identificarlo facilmente.'),
        verbose_name=_('Pseudónimo')
    )
    nombre_fabricante = models.CharField(
        max_length=60,
        help_text=_(
            'Nombre largo que le da el fabricante al producto.'
        ),
        verbose_name=_('Nombre real')
    )
    fabricante = models.ForeignKey(
        'Fabricante',
        on_delete=models.SET_NULL,
        blank=True,
        null=True
    )
    # etc...

As you can see, Articulo model acts as a through intermediary model to retrieve additional info.如您所见,Articulo model 充当通过中介 model 检索附加信息。 I'm trying to iterate over all the Articulo objects associated with a given Borrador object.我正在尝试遍历与给定 Borrador object 关联的所有 Articulo 对象。 At the moment I got it working by doing this:目前,我通过这样做使其工作:

class Borrador(models.Model):

    # [...]

    def tramitar(self, usuario, solicitar=False):

        articulos = self.productos.through.objects.filter(
            borrador=self
        )
        for articulo in articulos:
            # do stuff

My first attempt was the one below, but it returns all Articulo objects in the database我的第一次尝试是下面的,但它返回数据库中的所有Articulo 对象

articulos = self.productos.through.objects.all()
for articulo in articulos:
    # do stuff

Is there a better way to do this?有一个更好的方法吗? I imagined a simple self.productos.through shoul work, but it isn't the case...我想象了一个简单的self.productos.through工作,但事实并非如此......

Thanks in advance.提前致谢。 J. J。

You can access the Articulo s through the related_name=… parameter [Django-doc] of the ForeignKey :您可以通过ForeignKeyrelated_name=…参数 [Django-doc]访问Articulo

def tramitar(self, usuario, solicitar=False):
    articulos = self.articulo_set.all()
    # …

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM