[英]Django choices. How to set a option to be selected only once
I am working on a blog. 我正在写博客。 I have a section where there will be a special post.
我在一节中会有一个特别的帖子。 And another page where I have collection of special posts.
还有另一页,其中有我的特别文章集。 Here is my model.py
这是我的模型
class Post(models.Model):
post = models.TextField()
SPECIAL = (
('0', 'Special Post'),
('1', 'General Post'),
('2', 'Inactive Special Post'),
)
specialpost = models.CharField(max_length=1, choices=SPECIAL, default='1', )
Only One post should be in the Special Post. 特别职位中只能有一个职位。 When new special post is added, the old special post should be shifted to Inactive Special Post.
添加新的特殊职位后,旧的特殊职位应转换为非活动特殊职位。 So it can be shown in the Collection of Special post page.
因此,它可以显示在“特殊帖子集”页面中。 How can I do this?
我怎样才能做到这一点?
As @neeraj-kumar mentioned in comment, you can achieve this by overriding model's save()
method. 正如@ neeraj-kumar在评论中提到的那样,您可以通过重写模型的
save()
方法来实现此目的。 Add to Post class something like this: 在Post类中添加如下内容:
class Post(models.Model):
...
def save(self, *args, **kwargs):
special_post = Post.objects.filter(specialpost='0')
if self.specialpost == '0' and special_post:
special_post.update(specialpost='2')
super(Post, self).save(*args, **kwargs)
when you add a new post, filter the query like this change_actual_post = Post.objects.get(specialpost=0)
and then change the status of your old post change_actual_post.specialpost = 2
finally save change_actual_post.save()
. 当您添加新帖子时,请像这样
change_actual_post = Post.objects.get(specialpost=0)
查询条件: change_actual_post = Post.objects.get(specialpost=0)
,然后更改旧帖子的状态change_actual_post.specialpost = 2
最后保存change_actual_post.save()
。
Add these 3 lines into your views.py file before add a new special post 在添加新的特殊帖子之前,将这3行添加到您的views.py文件中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.