如何在django中进行内连接

时间:2015-03-11 06:05:08

标签: python django orm

我有三张表格如下

CurrentDiscount -

ItemID  | DiscountID
-----------------------
 1      |  2
 4      |  8

AvailableDiscounts -

DiscountID  |   ItemID  | Description
--------------------------------------
1           |   1       | '30% off'
2           |   1       | '10% off'
3           |   1       | 'Buy One Get One' 
4           |   4       | '30% off'
5           |   4       | 'Upto 20% off'
6           |   4       | '30% off'

自动生成折扣ID。

我想获取当前可用折扣的对象,如下所示 -

select AvailableDiscounts.* from CurrentDiscount Inner Join AvailableDiscounts Using (DiscountID)

我想要AvailableDiscounts对象的列表。 Django会对此进行什么查询?

class CurrentDiscount(models.Model):
    item = models.ForeignKey(Item, primary_key=True)
    discount = models.ForeignKey(AvailableDiscounts)

class AvailableDiscounts(models.Model):
    item = models.ForeignKey(Item)
    description = models.TextField()

2 个答案:

答案 0 :(得分:1)

current_discounts = CurrentDiscount.objects.all()

在视图中

for ds in current_discounts:
  print ds.discount.description

在html中

{% for ds in current_discounts %}
  {{ds.discount.description}}
{% endfor %}

答案 1 :(得分:0)

这是外键的问题。您可以设置外键Model,并使用

c = CurrentDiscount.objects.all()
c.availableDiscounts_set.all()