【问题标题】:How to check if data already exists in the table using django如何使用 django 检查表中是否已存在数据
【发布时间】:2019-11-08 22:40:32
【问题描述】:

我是 django 框架的新手,难以比较数据库中的值。 这是我在 models.py 中的表格:

class Post(models.Model):
   user = models.ForeignKey(User, on_delete=models.CASCADE,)
   title = models.CharField(max_length=200)
   content = models.TextField()
   creationDate = models.DateTimeField(auto_now_add=True)
   lastEditDate = models.DateTimeField(auto_now=True)

   def __str__(self):
       return self.title

class Votes(models.Model):
   user = models.ForeignKey(User, on_delete=models.CASCADE,)
   post_id = models.ForeignKey(Post, on_delete=models.CASCADE,)
   up_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)])
   down_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)])

   class Meta:
       unique_together = (("user","post_id"),) 

我在投票表中有这样的数据:

现在我想要检查上表,如果“user_id”和“post_id”已经存在于投票表的行中,如果存在的话,如果没有在 upvote 或 downvote 上添加价值,则抛出一条消息,我想每个人都明白我的意思如果没有,请告诉我。

我尝试过的是这段代码:

def chk_table():
    user_id = request.user
    post_id = id
    votes_table = Votes.objects.filter(user_id=user_id, post_id= post_id).exists()
    return votes_table

但是这个函数不仅仅在一行中检查孔表...

【问题讨论】:

  • 您的函数 chk_table 完全按照您的描述进行。不知道是什么问题
  • 附带说明,您不应该缩短函数名称。 check_table 更具可读性
  • 你也可以从这个answer使用Django的get_or_create方法。

标签: django database


【解决方案1】:

假设,在你的urls.py

from django.urls import path
from .views import add_vote

urlpatterns = [
    path('post/<int:post_id>/vote/add/', add_vote, name='add-vote'),
]

在你的views.py

from django.shortcuts import redirect, render

def add_vote(request, post_id):
    if request.method == 'POST':
        # receive your POST data here
        user_id = request.user.id
        post_id = post_id
        if not Votes.objects.filter(user_id=user_id, post_id=post_id).exists():
            Votes.objects.create(**your_data)
        redirect('your-desired-url')
    else:
        # your logic here

【讨论】:

  • 非常感谢您知道我使用了这种方法并且效果很好。
【解决方案2】:

我看到你已经在Meta 中定义了unique_together,所以你可以使用try except

from django.db import IntegrityError

try:
    # your model create or update code here
except IntegrityError as e: 
    if 'unique constraint' in e.message:
        # duplicate detected

【讨论】:

  • 感谢您的回答我使用了其他方法我没有使用此方法,因为我修改了其他错误。
猜你喜欢
  • 2012-07-06
  • 2021-06-13
  • 2021-05-24
  • 1970-01-01
  • 2019-11-25
  • 1970-01-01
  • 2015-06-17
  • 1970-01-01
  • 2014-04-10
相关资源
最近更新 更多