我目前有評論功能,我想為每個用戶添加一條評論的限制,但不知道該怎么做。我堅持在用戶模型中創建一個“已發布”欄位,當用戶發布評論時這是正確的,但我不知道該怎么做,最重要的是,這是否是更好的方法......
class Comment(models.Model):
service = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='comments')
author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,)
content = models.CharField(max_length=200, null=False, blank=True)
date = models.DateTimeField(auto_now_add=True)
def get_absolute_url(self):
return reverse('product-feedback', kwargs={'pk': self.pk})
class ProductFeedbackView(DetailView):
model = Product
template_name = 'services/product-feedback.html'
def get_context_data(self , **kwargs):
data = super().get_context_data(**kwargs)
connected_comments = Comment.objects.filter(service=self.get_object())
number_of_comments = connected_comments.count()
data['comments'] = connected_comments
data['no_of_comments'] = number_of_comments
data['comment_form'] = CommentForm()
return data
def post(self , request , *args , **kwargs):
if self.request.method == 'POST':
comment_form = CommentForm(self.request.POST)
if comment_form.is_valid():
content = comment_form.cleaned_data['content']
new_comment = Comment(content=content, author=self.request.user , service=self.get_object())
new_comment.save()
return redirect(self.request.path_info)
{% block content %}
{% if user.is_authenticated %}
<form action="" method="POST" id="main_form" class="comment_form">
<div>
<label for="comment">Type Comment here</label>
{{ comment_form.content }} {% csrf_token %} <input type="submit" value="Post"></div>
</div>
</form>
{% else %}
<h2>You need to Login to comment</h2>
{% endif %}
{% for comment in comments %}
<h3> <b>{{ comment.author }} : </b> {{ comment.content }}</h3>
{% endfor %}
{% endblock content %}
uj5u.com熱心網友回復:
如果您確實確定用戶應該發布一條且僅一條評論,則應使用 OneToOneField。這樣就可以自動生成唯一性約束,使物件更易于管理。
class Comment(models.Model):
service = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='comments')
author = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True,)
content = models.CharField(max_length=200, null=False, blank=True)
如果您希望用戶對每個產品只發表一條評論,但仍允許他對任意數量的產品發表評論,您應該在 Meta 類中添加一個約束:
class Comment(models.Model):
service = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='comments')
author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,)
content = models.CharField(max_length=200, null=False, blank=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=["service", "author"], name="One comment per user per product")
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/531288.html
下一篇:比較Access資料庫中的3個表
