归档 2015年4月

Django关联模型排序返回重复元素解决方法

在Django ORM中,使用order_by()方法对包含关联关系的模型进行排序时,返回结果中可能会出现重复元素。

假设有下面的两个模型Client和Interaction,Client为顾客,Interaction为交互。

Client类中包含顾客的姓名和联系方式,Interaction类中包含标题、时间、待办事项、截止日期。

class Client(models.Model):
    name = models.CharField(max_length=255, unique=True)
    contact = models.CharField(max_length=255, null=True, blank=True)

class Interaction(models.Model):
    client = models.ForeignKey(Client)
    title = models.TextField()
    when = models.DateTimeField()
    todo = models.TextField(null=True, blank=True)
    deadline = models.DateTimeField(null=True, blank=True)

现在想要查询按照交互的截止日期倒序排列的客户列表。

'clients' : Client.objects.all().order_by('-interaction__deadline'),

返回结果中包含重复元素。由于Client和Interaction为一对多的关系,因此对于每一个Interaction都返回了一个Client元素,而非仅仅是对结果进行排序。大家提到需要使用distinct(),但是distinct()对于这个特例并不适用,因为考虑到它们彼此之间存在的关联关系,结果返回值已经唯一的了。

通过Google,我发现了解决方法!相关博文链接:http://archlinux.me/dusty/2010/12/07/django-dont-use-distinct-and-order_by-across-relations/ ...

继续阅读

[LeetCode]Bitwise AND of Numbers Range

题目描述:

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

For example, given the range [5, 7], you should return 4.

题目大意:

给定范围[m, n],其中 0 <= ...

继续阅读

[LeetCode]Longest Substring Without Repeating Characters

题目描述:

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the ...

继续阅读

每日归档

上个月

下个月

归档