【问题标题】:Django: Collecting all entries from a Foreign key model from a specific Parent ModelDjango:从特定父模型的外键模型中收集所有条目
【发布时间】:2014-06-12 21:49:52
【问题描述】:

我目前正在使用这种关系从模型Product 的特定实例中获取所有图像

product = get_object_or_404(Product, pk=product_id)
images = product.image_set.all()

如果我开始删除和重新排列图像,则该集合不会正确更新自身并包含旧图像并且只是保持其原始顺序。

我相信解决此问题的方法是直接通过Image 模型定义images,而不是作为Product 的集合。

这样做:

images = Image.objects.all()

返回每个产品的所有图像。有没有办法我可以使用类似的方法,直接从Image 模型调用图像,只针对活动产品的图像集?类似于:

images = Image.objects.all(product_id)

【问题讨论】:

    标签: python django apache postgresql


    【解决方案1】:

    你应该可以做到:

    Image.objects.filter(product__product_id=pk)
    

    或者

    Image.objects.filter(product__pk=product_id)
    

    如果“pk”是变量并且“product_id”是列名,则使用第一个示例,反之亦然。另外,请注意filter(product__pk=product_id)product 之后的双下划线。

    【讨论】:

    • 您的解决方案都给出了错误,但是在根据您的建议进行了一些混乱之后,我想我已经弄清楚了。我的图像模型看起来像这样://// product_image = models.ForeignKey(Product) image = models.ImageField(upload_to='image',blank=True) //// 所以这最终可以工作(我认为,需要做更多的测试)///// images = Image.objects.filter(product_image_id=product_id)
    猜你喜欢
    • 2016-04-26
    • 2020-12-18
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    • 2020-02-02
    • 2013-01-17
    • 1970-01-01
    • 2015-03-07
    相关资源
    最近更新 更多