簡體   English   中英

如何在Django中進行內部聯接

[英]How to do inner join in django

我有以下三個表

當前折扣-

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

可用折扣-

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()
current_discounts = CurrentDiscount.objects.all()

視野中

for ds in current_discounts:
  print ds.discount.description

在html中

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

這是一個外來的問題。 您可以設置一個forignkeyModel並使用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM