Django:按计算标准排序(高级案例)

Django:按计算标准排序(高级案例),django,django-models,django-queryset,django-orm,Django,Django Models,Django Queryset,Django Orm,型号: 假设: class Customer(models.Model): name = models.CharField(max_length=200) time_categoty = models.IntegerField() importance = models.IntegerField() class Interaction(models.Model): i_date = models.DateTimeField() class Interactio

型号:

假设:

class Customer(models.Model):
    name = models.CharField(max_length=200)
    time_categoty = models.IntegerField()
    importance = models.IntegerField()

class Interaction(models.Model):
    i_date = models.DateTimeField()

class Interaction_customer(models.Model):
    interaction = models.ForeignKey(Interaction)
    customer = models.ForeignKey(Customer)
(即给定客户的最新交互)

需要:按标准排序的所有客户列表: 时间\类别/(datetime.now()-x)*c.重要性

请不要在djangoproject.com上给我一个“额外”的链接,我已经仔细阅读了它,但我真的不知道如何在我的案例中实现它。(案子很棘手,一周没人能帮上忙,django绝地被通缉) 如有任何建设性意见,将不胜感激。
谢谢//Ed

这里有一个与第三个模型的多个关系,用于获取额外数据。通过链接它们,您可以获得直接连接它们的api的额外好处(这似乎是必要的)。现在,对于手头的问题,让我们先创建一个方法,让客户计算该数据:

c = Customer.objects.get(pk=1)
x = Interaction.objects.filter(interaction_person__person=c).latest('i_date').i_date
现在我们要按它排序。您可以使用python实现这一点:

class Customer(models.Model):
    name = models.CharField(max_length=200)
    time_category = models.IntegerField()
    importance = models.IntegerField()
    interactions = models.ManyToManyField('Interaction', through='InteractionCustomer')

    def delta(self):
        ia = self.interactions.latest('i_date').i_date
        return self.time_categoty / ( datetime.now() - ia ) * self.importance

class Interaction(models.Model):
    i_date = models.DateTimeField()

class InteractionCustomer(models.Model):
    interaction = models.ForeignKey(Interaction)
    customer = models.ForeignKey(Customer)
或者,为了提高效率,您可以将其保存到另一个字段。虽然在这种情况下,您需要不断更新它。您可以重写save方法,但这仅在保存手头的Customer对象时适用,这种情况可能并不总是如此(因此在以这种方式实现它时需要仔细考虑):


对不起,交互用户==交互用户1。最好将计算结果保存在某个地方,以便于排序(没有其他明确的方法可以做到这一点而不牺牲一些效率)2。你的模特儿看起来像个大傻瓜。我不知道这是否是你所说的“额外”的意思,我完全不理解如果客户不添加任何其他字段,你需要与客户进行什么交互。最好直接链接它们我已经删除了所有与案例无关的字段,但real base只需要这样一个结构//EDI使用“通过”的ManyToMany有什么异议吗?看起来像是你要找的设计没错。这就是“通过”的目的。请参阅我的答案以了解详细的实现。这只会让他们之间的联系更容易直接感谢你的专业精神和乐于帮助!该方法易于实现,效果良好!当然可以很高兴能帮上忙=]
 sorted( Customer.objects.all(), key=lambda x: x.delta() )
class Customer(models.Model):
    ....
    delta = models.IntegerField()

    def save(self, *args, **kwargs):
        self.delta = self.calc_delta()
        super(Customer, self).save(*args, **kwargs)