我已尝试通过PublisherPolicyManager使用BasePolicy中“进程” ForeignKey的“ policies” related_name进行反向查询。产生错误:
AttributeError: 'RelatedManager' object has no attribute 'valid'
是否有一种方法,PublishedPolicy类可以为'process'字段分配一个不同的related_name,以允许Process反向查询指向PublishedPolicy而不是BasePolicy?
还是逻辑完全有缺陷?
class BasePolicy(models.Model):
title = models.CharField(max_length = 100)
process = models.ForeignKey(Process, null=True, blank=True, on_delete=models.SET_NULL, related_name='policies')
force_read_again = models.BooleanField(default=False)
class DraftPolicy(BasePolicy):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def publish(self):
PublishedPolicy.objects.create(
draft_policy = self,
title=self.title,
policy=self.policy,
force_read_again=self.force_read_again)
process=self.process)
class PublishedPolicyManager(models.Manager):
def current(self):
return super().get_queryset().exclude(archived_at__isnull=True)
def valid(self):
print('here')
return super().get_queryset().exclude(force_read_again=True, archived_at__isnull=False)
class PublishedPolicy(BasePolicy):
objects = PublishedPolicyManager()
draft_policy = models.ForeignKey(DraftPolicy, on_delete=models.SET_NULL, null=True)
published_at = models.DateTimeField(auto_now_add=True)
archived_at = models.DateTimeField(null=True)
class PolicyReadManager(models.Manager):
def valid(self):
return super().filter(policy__in=PublishedPolicy.objects.valid())
class PolicyRead(models.Model):
objects = PolicyReadManager()
policy = models.ForeignKey(PublishedPolicy, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='policies_read')
read_at = models.DateTimeField(auto_now=True)
def __str__(self):
return '{user} read {policy} at {read_at}'.format(user=user, policy=policy, read_at=read_at)
class Process(models.Model):
name = models.CharField(max_length=50)
description = models.TextField()
class ProcessAllocation(models.Model):
process = models.ForeignKey(Process, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
allocated_at = models.DateTimeField(auto_now=True, editable=False)
def policies_outstanding(self):
policies = self.process.policies(manager='objects').valid()
read = self.user.policies_read(manager='objects').valid()
return policies.exclude(id__in=read)