django模型外键访问两个模型的属性

django model foreign key Accessing attributes of both models

我的代码:

products = Clothing.objects.select_related('product')
for product in products:
   print(product.category+"  "+product.price)

失败:

AttributeError: 'Clothing' object has no attribute 'price' [13/Jan/2019 13:31:53] "GET /mens_product/ HTTP/1.1" 500 65348

当您在 Clothing 模型中与 Product 有外键关系时,您可以使用以下方法获取所有关联产品:

products = Product.objects.filter(clothing=a_clothing_instance)

如果您想使用 shorthand,您可能正在寻找 RelatedManager。在 ForeignKey 场景中,您将拥有:

class Clothing(models.Model):
    ....

class Product(models.Model):
    clothing = models.ForeignKey(clothing)

然后您可以调用所有产品:

products = clothing.product_set.all()