返回所有用户债务的查询集?

时间:2017-08-05 15:33:42

标签: python django-models django-rest-framework django-queryset django-managers

我有一个连接Android客户端的django rest api。 django rest framework api上的一个模型称为Debt

class Debt(models.Model):
    paying_user = models.ForeignKey(User, related_name="paying_user")
    receiving_user = models.ForeignKey(User, related_name="reeceiving_user")
    amount = models.FloatField()
    currency = models.CharField(max_length=10, default="USD")
    description = models.CharField(max_length=100, blank=True)
    date_incurred = models.DateTimeField(default=timezone.now)
    deadline = models.DateTimeField()
    payed = models.BooleanField(default=False)
    overdue = models.BooleanField(default=False)

    class Meta:
        verbose_name = "Debt"
        verbose_name_plural = "Debts"

    objects = DebtManager()

    def save(self, *args, **kwargs):
        if self.paying_user == self.receiving_user:
            raise ValidationError("Users cannot be in debt with themselves.")
        super(Debt, self).save(*args, **kwargs)

DebtManager我有一个名为all_debt的函数:

def all_debts(self, user):
    ''' Returns a queryset of all a user's debts '''
    all_debt_queryset = ... # What do I write here?
    return all_debt_queryset

要检索所有用户的债务,我需要获取Debt属性等于paying_user参数(当前用户)和所有user个对象的所有Debt个对象其中receiving_user属性等于user参数。

如何获取包含所有用户债务的查询集?

1 个答案:

答案 0 :(得分:2)

您可以使用过滤器并只返回查询集。我假设你在方法参数中发送用户对象。

from django.db.models import Q
def all_debts(self, user):
    return self.objects.filter(Q(paying_user=user) | Q(receiving_user=user))

注意:我建议从DebtManager删除all_debts函数。它不适合成为经理的职能。虽然它更适合Debt模型的功能