Django error: The QuerySet value for an exact lookup must be limited to one result using slicing?

Django error: The QuerySet value for an exact lookup must be limited to one result using slicing?

我有以下模型架构:


class Site(models.Model):
    name = models.CharField(max_length=255)
    location = models.OneToOneField(GeoLocation, on_delete=models.PROTECT,
                                    related_name=RelatedNames.ADDRESS,
                                    blank=True, null=True)

    account = models.ForeignKey(Account, on_delete=models.PROTECT, related_name=RelatedNames.ACCOUNT_SITES)
    _type = models.IntegerField(choices=SiteTypeChoices.CHOICES)
    primary_email = models.EmailField(null=True, blank=True)

    objects = models.Manager()

    def __str__(self):
        return self.name

    def get_site_address(self):
        return str(self.location)


class SiteScore(models.Model):
    site = models.ForeignKey(Site, on_delete=models.CASCADE, related_name=RelatedNames.SITE_SCORES)
    date = models.DateTimeField(default=timezone.now)
    score = models.IntegerField(default=0)
    score_type = models.IntegerField(choices=SiteScoreChoices.CHOICES, null=True, blank=True)

class CustomUser(AbstractUser)
    username = None
    email = models.EmailField(_(Fields.EMAIL_ADDRESS), unique=True)

    accessed_sites = models.ManyToManyField(Site, related_name=RelatedNames.USERS)
    
    USERNAME_FIELD = Fields.EMAIL
    REQUIRED_FIELDS = []

我正在尝试按日期和连接到网站的用户过滤掉网站分数:

today = timezone.now().date()
worst_scores = SiteScore.objects.filter(date__date=today, site__users=self.request.user).order_by('-score')

但这会引发此错误:

The QuerySet value for an exact lookup must be limited to one result using slicing.

还尝试使用:

        worst_scores = SiteScore.objects.filter(date__date=today, site__users__in=self.request.user)

但出现错误:

'CustomUser' object is not iterable

很少有可能的解决方案

date__date=today

返回的结果 > 1,因此失败。你能尝试传递一个更准确的今天对象(e.g.custom 形成的)并检查它是否有效吗?

这会发生什么

worst_scores = SiteScore.objects.filter(date__date=today, site__users=self.request.user).order_by('-score')[0] 

如果您只想按一项进行过滤,请尝试使用 .get() 而不是 filter()

对于几个,你可以使用 __in,例如

products = Product.objects.filter(seller<b>__in</b>=account)

因此 __in lookup [Django-doc]