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

Returning queryset of all a user's debts?

我有一个 android 客户端连接到的 django rest api。 django rest 框架 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 参数的对象。

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

您可以使用过滤器并简单地 return 查询集。我假设您在方法参数中发送用户对象。

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 模型的功能