When I define a custom manager .. Error:Manager isn't accessible via Post instances
When I define a custom manager .. Error:Manager isn't accessible via Post instances
我定义了一个继承模型的自定义管理器。经理放入我的模型 'Post'。
错误说你不能通过实例调用管理器,但我没有通过实例调用它,当我删除自定义管理器时它工作正常。
models.py:
class PublishedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='Published')
class Post(models.Model):
STATUS_CHOICES = [
('draft','Draft'), ('published','Published'),
]
id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
published = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='Published')
author = models.ForeignKey(CustomUser,on_delete=models.CASCADE)
body = models.TextField()
objects = models.Manager()
published = PublishedManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("detail", kwargs={"slug":self.slug,"id": self.id})
views.py:
class PostListView(ListView):
model = Post
template_name = 'blog/index.html'
context_object_name='posts'
Error image
我认为你不能有一个与模型字段同名的经理。尝试将其重命名为 published_objects
.
当您尝试访问 post.published
(一个字段)时发生错误,但 Django 认为您想要访问管理器,因此出现错误。
我定义了一个继承模型的自定义管理器。经理放入我的模型 'Post'。 错误说你不能通过实例调用管理器,但我没有通过实例调用它,当我删除自定义管理器时它工作正常。
models.py:
class PublishedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='Published')
class Post(models.Model):
STATUS_CHOICES = [
('draft','Draft'), ('published','Published'),
]
id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
published = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='Published')
author = models.ForeignKey(CustomUser,on_delete=models.CASCADE)
body = models.TextField()
objects = models.Manager()
published = PublishedManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("detail", kwargs={"slug":self.slug,"id": self.id})
views.py:
class PostListView(ListView):
model = Post
template_name = 'blog/index.html'
context_object_name='posts'
Error image
我认为你不能有一个与模型字段同名的经理。尝试将其重命名为 published_objects
.
当您尝试访问 post.published
(一个字段)时发生错误,但 Django 认为您想要访问管理器,因此出现错误。