【发布时间】: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