python - 防止数据库中数据重复

标签 python django

这是 View 中的代码,

def index(request):
    data = Model.objects.create(user=request.user, timestamp=timezone.now())

每当请求 View 时,我都会保存请求该 View 的用户以及用户请求该页面的时间戳。

但是,它在数据库中重复相同的数据并更新时间戳。如何在请求 View 时通过更新同一实例来防止重复?

请帮助我!

最佳答案

你可以用这种方式来处理。如果数据不存在,则创建其他更新。

def index(request):
    data = Model.objects.update_or_create(user=request.user, timestamp=timezone.now())

Alternatively:

def index(request):

    data = Model.objects.get(user=request.user)

    if not data:
        data = Model.objects.create(user=request.user, timestamp=timezone.now())
    else:
        data = Model.objects.update(user=request.user, timestamp=timezone.now())

关于python - 防止数据库中数据重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46260332/

相关文章:

python - 如何消除 sklearn 上决策树的随机性?

python - 如何在添加另一个 y 轴的同时旋转 x 标签?

python - Ruby 在 Python 中的 “method_missing”

django - 通过 Django shell 添加文件

python - 通过处理 500 处理程序中的一些错误并在这些情况下呈现正常的 HTTP 响应来明智地利用 ATOMIC_REQUESTS

django - "Add New"到 django 模型中的外键字段

python - Django 2.2 img 未加载

python - 使用多处理模块进行集群计算

python - 在函数中打印返回值,Python

Django-通过 celery 从模型执行任务