Python 通过模型对象在django m2m上迭代
在我的项目中,我有以下许多关系:Python 通过模型对象在django m2m上迭代,python,django,django-models,Python,Django,Django Models,在我的项目中,我有以下许多关系: class Borrador(models.Model): nombre = models.CharField( max_length=40, help_text=_('Nombre para identificar al borrador.') ) productos = models.ManyToManyField( Producto, through=Articulo
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...
正如您所看到的,Articulo模型充当了一个中介模型来检索其他信息。
我试图迭代与给定Borrador对象关联的所有Articulo对象。
当时,我通过这样做使它工作:
class Borrador(models.Model):
# [...]
def tramitar(self, usuario, solicitar=False):
articulos = self.productos.through.objects.filter(
borrador=self
)
for articulo in articulos:
# do stuff
我的第一次尝试是下面的一次,但它返回数据库中的所有Articulo对象
articulos = self.productos.through.objects.all()
for articulo in articulos:
# do stuff
有更好的方法吗?我想象了一个简单的self.productos.through
shoul工作,但事实并非如此
提前谢谢!
J.您可以通过
外键的访问Articulo
s:
def tramitar(self, usuario, solicitar=False):
articulos = self.articulo_set.all()
# …
def tramitar(self、usuario、requestar=False):
articulos=self.articulo_set.all()
#…
你就不能只做Borrador.Articulo.all()
?还没有尝试过,但我认为威廉的答案是正确的。谢谢你!哦,该死的,我太专注于m2m关系了,以至于我忘了我有一个可以使用的外键(就像我在同一个项目中多次做的那样)。谢谢!