使用Python从数据库获取数据(Django框架)

1 投票
3 回答
6556 浏览
提问于 2025-04-15 16:36

通常情况下,如果我要写一个SQL语句,我会这样做,

    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 

那么我该如何用Django的方式,通过API来查询数据库呢,也就是说,

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

我的模型是

BASE ACCOUNT
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
ACCOUNT
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)
ADDRESS
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]

3 个回答

2

先别管SQL了。你想通过这个查询达到什么目的?你想对结果做些什么?

你没有提供你的模型。它们有定义外键吗?你能不能简单地查询一下,使用 select_related() 来获取关联的对象?

补充说明 上次你问这个问题时,给出的答案有什么问题吗?查看这里

再次补充 但大家都已经告诉你怎么通过外键获取项目了!别管id了,你根本不需要它。如果你有一个 Account 对象 a,你只需要用 a.default_address 就能获取到关联的 Address 对象。如果这样不行,那说明你没有提供正确的模型,因为用你提供的模型肯定能成功。

2

Django 提供了一种简单的方法,让你在处理复杂查询时可以直接使用原生 SQL。你可以查看官方文档了解更多信息:执行原始 SQL 查询

8

“通常如果我在写SQL语句的话”

欢迎来到ORM的世界。你现在不是在写SQL,所以把这个从问题中去掉。不要发SQL并问怎么把SQL翻译成ORM。这样做只会限制你学习的能力。别再这样了。

先写下你想要的结果是什么。

看起来你现在获取的是所有的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的术语来描述你想要的东西了。

撰写回答