2009-12-02 82 views
0

通常如果我寫一個SQL語句來這個,我會做這樣的事情,從蟒蛇數據庫(上Django框架)獲取數據

SELECT * FROM (django_baseaccount LEFT JOIN django_account ON django_baseaccount.user_id = django_account.baseaccount_ptr_id) 
LEFT JOIN django_address ON django_account.baseaccount_ptr_id = django_address.user_id;name 

我怎麼把這個變成查詢的Djagno方式使用API​​的數據庫,即

TradeDownloads.objects.filter(online=1)[:6] 

我的模型 基本帳戶

class BaseAccount(models.Model): 
user = models.ForeignKey(User, unique=True) 

def __unicode__(self): 
    """ 
    Return the unicode representation of this customer, which is the user's 
    full name, if set, otherwise, the user's username 
    """ 
    fn = self.user.get_full_name() 
    if fn: 
     return fn 
    return self.user.username 

def user_name(self): 
    """ 
    Returns the full name of the related user object 
    """ 
    return self.user.get_full_name() 

def email(self): 
    """ 
    Return the email address of the related user object 
    """ 
    return self.user.email 

帳戶

class Account(BaseAccount): 
""" 
The account is an extension of the Django user and serves as the profile 
object in user.get_profile() for shop purchases and sessions 
""" 
telephone = models.CharField(max_length=32) 
default_address = models.ForeignKey(Address, related_name='billing_account', blank=True, null=True) 
security_question = models.ForeignKey(SecurityQuestion) 
security_answer = models.CharField(max_length=200) 
how_heard = models.CharField("How did you hear about us?", max_length=100) 
feedback = models.TextField(blank=True) 
opt_in = models.BooleanField("Subscribe to mailing list", help_text="Please tick here if you would like to receive updates from %s" % Site.objects.get_current().name) 
temporary = models.BooleanField() 

def has_placed_orders(self): 
    """ 
    Returns True if the user has placed at least one order, False otherwise 
    """ 
    return self.order_set.count() > 0 

def get_last_order(self): 
    """ 
    Returns the latest order that this customer has placed. If no orders 
    have been placed, then None is returned 
    """ 
    try: 
     return self.order_set.all().order_by('-date')[0] 
    except IndexError: 
     return None 

def get_currency(self): 
    """ 
    Get the currency for this customer. If global currencies are enabled 
    (settings.ENABLE_GLOBAL_CURRENCIES) then this function will return 
    the currency related to their default address, otherwise, it returns 
    the site default 
    """ 
    if settings.ENABLE_GLOBAL_CURRENCIES: 
     return self.default_address.country.currency 
    return Currency.get_default_currency() 
currency = property(get_currency) 

def get_gateway_currency(self): 
    """ 
    Get the currency that an order will be put through protx with. If protx 
    currencies are enabled (settings.ENABLE_PROTX_CURRENCIES), then the 
    currency will be the same returned by get_currency, otherwise, the 
    site default is used 
    """ 
    if settings.ENABLE_PROTX_CURRENCIES and settings.ENABLE_GLOBAL_CURRENCIES: 
     return self.currency 
    return Currency.get_default_currency() 
gateway_currency = property(get_gateway_currency) 

地址

class Address(models.Model): 
""" 
This class encapsulates the data required for postage and payment mechanisms 
across the site. Each address is associated with a single store account 
""" 
trade_user = models.BooleanField("Are you a stockist of N Products", help_text="Please here if you are a Stockist") 
company_name = models.CharField(max_length=32, blank=True) 
line1 = models.CharField(max_length=200) 
line2 = models.CharField(max_length=200, blank=True) 
line3 = models.CharField(max_length=200, blank=True) 
city = models.CharField(max_length=32) 
county = models.CharField(max_length=32) 
postcode = models.CharField(max_length=12) 
country = models.ForeignKey(Country) 
account = models.ForeignKey('Account') 

class Meta: 
    """ 
    Django meta options 

    verbose_name_plural = "Addresses" 
    """ 
    verbose_name_plural = "Addresses" 

def __unicode__(self): 
    """ 
    The unicode representation of this address, the postcode plus the county 
    """ 
    return ', '.join((self.postcode, str(self.county))) 

def line_list(self): 
    """ 
    Return a list of all of this objects address lines that are not blank, 
    in the natural order that you'd expect to see them. This is useful for 
    outputting to a template with the aid of python String.join() 
    """ 
    return [val for val in (self.line1, self.line2, self.line3, self.city, self.county, self.postcode, self.country.name) if val] 
+0

只是爲了澄清 - 它不是一個「Python方式」。這是** django **的方式。Python與django關於如何提供API – nosklo 2009-12-02 10:26:14

回答

7

「通常,如果我在寫SQL語句」

歡迎ORM。你不是在寫SQL,所以這個問題中刪除了這個。不要發佈SQL並詢問如何將SQL轉換爲ORM。翻譯SQL會限制你的學習能力。停止這樣做。

寫下結果應該是什麼。

看起來您正在獲取所有Account對象。期。 也可以在視圖函數或模板中的某個位置獲取Address

for a in Account.objects.all(): 
    a.default_address # this is the address that SQL brought in via a "join". 

就是這樣。實際上請做Django教程中的所有示例。實際上從示例中輸入代碼並查看它是如何工作的。

所有「連接」操作都是SQL解決方法。它們是一個奇怪的SQL主題,並且與底層對象無關。所以停止使用SQL術語來描述你想要的東西。

+0

這是我可以解釋它的最好方式,這對我來說都是非常新的被扔進了從未碰過Python或Django的深處。 – Udders 2009-12-02 11:36:22

+0

這現在可以工作,我無法使用這個到達地址細節,我可以得到到默認的地址ID,但它是 – Udders 2009-12-02 11:43:52

+0

工作很好只是不得不改變帳戶的地址 – Udders 2009-12-02 12:02:06

1

Django提供了一個乾淨的方式落回至本地SQL複雜查詢看到官方文檔:Performing raw SQL queries

+0

的決定無關。感謝您在這些示例中澄清'%s'是什麼意思,以及如何將變量傳遞給查詢? – Udders 2009-12-02 11:01:33

+0

雖然這可能會有所幫助,但我將這個問題看作是詢問如何使用Django的ORM將該特定的SQL查詢轉換爲等效的QuerySet。 – 2009-12-02 11:03:08

1

忘記SQL。你想從這個查詢中獲得什麼?你想對結果做什麼?

您還未發佈模型。他們是否定義了外鍵?你可以做一個簡單的查詢並使用select_related()來獲取連接的對象嗎?

編輯爲添加給出的答案the previous time you asked this question有什麼問題?

再次編輯但每個人都已經告訴你如何通過外鍵獲取該項目!忘記身份證,你不需要它。如果您有Account對象a,則只需執行a.default_address即可獲取與之相關的實際Address對象。如果這不起作用,那麼你不會發布正確的模型,因爲這肯定會與你發佈的模型一起工作。

+0

我正在嘗試確定登錄的用戶是否是交易用戶,無論是反向還是反向(查找他們是否爲交易用戶,是決定是否導航到某個頁面 – Udders 2009-12-02 11:18:46

+0

添加在我原來的查詢中提到的類 – Udders 2009-12-02 11:19:18

+0

原始問題中的答案有什麼問題? – 2009-12-02 11:25:26