小编Bar*_*rmi的帖子

Django和Postgres的get_or_create失败(重复键值违反了唯一约束)

感谢您花时间阅读我的问题.

我有一个带有以下型号的django应用程序:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    ...

class Visit(models.Model):
    profile = models.ForeignKey(UserProfile)
    date = models.DateField(auto_now_add=True, db_index=True)
    ip = models.IPAddressField()
    class Meta:
        unique_together = ('profile', 'date', 'ip')
Run Code Online (Sandbox Code Playgroud)

在一个视图中:

profile = get_object_or_404(Profile, pk = ...)
get, create = Visit.objects.get_or_create(profile=profile, date=now.date(), ip=request.META['REMOTE_ADDR'])
if create: DO SOMETHING
Run Code Online (Sandbox Code Playgroud)

一切正常,但Postgres日志已满,重复键错误:

2012-02-15 14:13:44 CET ERROR:  duplicate key value violates unique constraint "table_visit_profile_id_key"
2012-02-15 14:13:44 CET STATEMENT:  INSERT INTO "table_visit" ("profile_id", "date", "ip") VALUES (1111, E'2012-02-15', E'xx.xx.xxx.xxx') RETURNING "table_visit"."id"
Run Code Online (Sandbox Code Playgroud)

试过不同的解决方案,例如

from django.db import transaction 
from django.db import …
Run Code Online (Sandbox Code Playgroud)

django postgresql

9
推荐指数
2
解决办法
3605
查看次数

标签 统计

django ×1

postgresql ×1