我有一个连接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
参数。
如何获取包含所有用户债务的查询集?
答案 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
模型的功能