Django排序/ order_by具有计算值

时间:2015-06-27 13:14:34

标签: python django sorting django-models

我有两个模型SlotAppointment

Slot对象基本上是User的约会请求,它们是为week_starting DateField定义的,我需要匹配两个插槽来为{{1}创建一个约会对象}。我正在迭代插槽并创建约会,如下所示:

week_starting

while Slot.objects.filter(week_starting=next_weekday(datetime.datetime.today(), 0), is_matched=False).count() > 1: slot = Slot.objects.filter(week_starting=next_weekday(datetime.datetime.today(), 0), is_matched=False)[:1].get() users = User.objects.filter(~Q(id=slot.user.id)) min_count = Appointment.objects.filter(users_id=slot.user.id).filter(users_id=users[0].id).count() for user in users: if Appointment.objects.filter(users_id=slot.user.id).filter(users_id=user.id).count() < min_count and Slot.objects.filter(Q(user=user) & Q(is_matched=False) & Q(week_starting=next_weekday(datetime.datetime.today()))).count() > 0: min_count = Appointment.objects.filter(users_id=slot.user.id).filter(users_id=user.id).count() temp_slot = Slot.objects.filter(Q(user=user) & Q(is_matched=False) & Q(week_starting=next_weekday(datetime.datetime.today())))[:1].get() slot_to_match = temp_slot appointment = Appointment(week_starting=slot.week_starting) appointment.users.add(slot.user) appointment.users.add(slot_to_match.user) appointment.save() slot.is_matched = True slot.matched_on = datetime.datetime.now() slot.save() slot_to_match.is_matched = True slot_to_match.matched_on = datetime.datetime.now() slot_to_match.save() 是一种方法,可以找到下一个星期一的日期。

刚刚出现了新的要求,显然我需要根据用户的情况匹配插槽。以前的约会一起计算,即对于任何一个插槽,我需要找到另一个,其中用户的预约数量少于其他人。

next_weekday型号:

Slot

class Slot(models.Model): user = models.ForeignKey(User) week_starting = models.DateField() is_matched = models.BooleanField(default=False, blank=False, null=False) matched_on = models.DateTimeField(blank=True, null=True) 型号:

Appointment

我需要匹配不是class Appointment(models.Model): week_starting = models.DateField() start_date = models.DateTimeField(null=True, blank=True) users = models.ManyToManyField(User, related_name='appointment_users') supervisor = models.OneToOneField(User, related_name='appointment_supervisor', null=True, blank=True, unique=False) 的两个Slot对象来创建is_matched对象。我需要为每个Slot对象做这件事。这样做时,我需要匹配两个Appointment个数最少的用户。

我不知道任何其他解决方案,但循环。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可能需要针对相关名称等进行调整,但以下内容应该有所帮助。如果我理解正确,您需要Slot个对象了解他们User的{​​{1}}次数。

Appointment

这将返回一个2元组的列表,其中第一项是用户,第二项是他们的约会计数。将这两个项目放在这样的列表中将为您提供两个相关用户,其中任何给定位置的预约最少。请记住处理列表中人数少于2人的情况,或者约会计数中存在关联的情况。

我可能会按照以下方式添加另一种模型方法:

# define as a method of your Slot class
def user_appointment_count(self):
    return [(x, x.appointment_set.count()) for x in self.user_set.all()]

如果你想根据他们的两个用户中的几个约会来排序插槽,你可以将它与我的第一个评论中作为查询集的建议(作为额外的上下文或作为主要查询集取决于你的偏好)相似。上面有。

def relevant_appointment_count(self):
    return sum(x[1] for x in self.user_appointment_count()[:2])

那应该(没有再测试过,可能需要稍微调整)按照我描述的顺序返回一个插槽列表。再次,您需要处理我之前描述的相同情况。