【问题标题】:How do i get field data from "through" ManyToMany object?如何从“通过”ManyToMany 对象获取字段数据?
【发布时间】:2018-02-14 03:43:25
【问题描述】:

我在如何在 ProductInsideCombo 中获取“组”数据时遇到了麻烦,这是一个与“通过”链接的 ManyToMany 对象。我需要获取“组”数据,请帮助。

这是我的两个模型:

@python_2_unicode_compatible
class ProductInsideCombo(models.Model):
    parent  = models.ForeignKey('Product', related_name='+')
    child   = models.ForeignKey('Product', verbose_name="Products inside the combo", related_name='+')
    group   = models.CharField(
        max_length=255,
        choices=(
            ('group_1', 'Group 1'),
            ('group_2', 'Group 2'),
        ),
        default='group_1',
    )

    def __str__(self):
        return str(self.id)


@python_2_unicode_compatible
class Product( models.Model ):
    name    = models.CharField(verbose_name="Name"), max_length=255)
    slug    = models.SlugField(verbose_name="Slug"), max_length=255, unique=True)

    price       = models.PositiveIntegerField(verbose_name='Price', null=True, blank=True)
    sale_price  = models.PositiveIntegerField(verbose_name="Sale Price", null=True, blank=True)

    products_inside_combo   = models.ManyToManyField('self', through='ProductInsideCombo', symmetrical=False, help_text="Only for Combo Products", blank=True)

    created         = models.DateTimeField(default=now)
    modified        = models.DateTimeField(editable=True, auto_now=True)

    def __str__(self):
        return "%s" % (self.sku, )

    class Meta:
        verbose_name        = "Product"
        verbose_name_plural = "Products"

这是我尝试过的:

the_product     = Product.objects.all().filter(id=5).first() # simplified query for stackoverflow

for one_product in the_product.products_inside_combo.all().order_by('products_inside_combo__id'):
        try1 = one_product.group # fail
        try2 = one_product.products_inside_combo__group # fail too!
        try3 = one_product.products_inside_combo.group # fail
        product_id = one_product.id

这是我目前的工作方式,但我觉得这是一个糟糕的查询:

 for one_product in the_product.products_inside_combo.all().order_by('products_inside_combo__id'):
        product_id          = one_product.id # child id
        # to get the Group data
        the_product_inside_combo    = ProductInsideCombo.objects.all().filter(parent__id=the_product.id, child__id=product_id).first()
        the_group_data              = the_product_inside_combo.group # this is what i want
        product_name        = one_product.name

【问题讨论】:

  • 您是否收到任何日志错误/调试错误,或者模板/数据库调用是否静默失败?
  • 问题是我无法在 ProductInsideCombo 中获取组数据。如果我能得到那个“组”字符串数据,问题就解决了。是的,那些“try1”、“try2”、“try3”都失败/抛出异常
  • 你能添加这个例外吗?
  • 我更新了问题以使其更清晰

标签: django python-2.7 django-models


【解决方案1】:

您可以将related_name 添加到您的ProductInsideCombo 模型中:

class ProductInsideCombo(models.Model):
     parent  = models.ForeignKey('Product', related_name='children')

并使用它来迭代所有产品的 productinsidecombos:

for one_product in the_product.children.all().order_by('id'):
    try1 = one_product.group # will fetch group

【讨论】:

  • 但它会破坏我已经使用 + 作为相关名称的旧查询吗?
  • @RaymondSeger + 只是禁用revesre 查找,请参阅文档docs.djangoproject.com/en/2.0/ref/models/fields/…,所以你现在没有这个。但是你可以添加它。由于这将是您项目的新功能,我认为这不会破坏任何东西。
  • 其实这是一个live project,哈哈,我只是简化了stackoverflow的代码
  • @RaymondSeger 你想说你已经有不等于+的related_name吗?在这种情况下,您不需要更改它,您可以使用它:for one_product in the_product.yout_related_name.all()
  • 不,我是说我一直使用 + 作为相关名称。恐怕如果我使用related_name。一切都崩溃了。
猜你喜欢
  • 1970-01-01
  • 2021-08-23
  • 2021-12-27
  • 1970-01-01
  • 2020-12-23
  • 2018-02-28
  • 2013-10-02
  • 2021-11-26
  • 2015-11-18
相关资源
最近更新 更多