Django模型创建数据重复

时间:2016-11-08 09:12:21

标签: python django

1.Models的名字是UserRecord 2.Below是我的观点代码。

@login_required
def data(request, page, keyword,strEncode):
    current_username = request.user.username
    data_s = dosomething() #It takes a long time!!!
    UserRecord.objects.get_or_create(user=User.objects.get(username=current_username),MyRecords=keyword) # in order to create unique value
    # or use below method
    # if not UserRecord.objects.filter(user=User.objects.get(username=current_username),MyRecords=keyword):
        # UserRecord.objects.create(user=User.objects.get(username=current_username),MyRecords=keyword)
    return JsonResponse(data_s, safe=False)

多次请求URL下面没有间隔,例如并发线程 http://127.0.0.1:8000/data/1/test/english/
完成此操作后,MyRecords列将填充重复值 我在Django文档中发现使用'with transaction.atomic'来处理这个问题,但它没有用。

2 个答案:

答案 0 :(得分:1)

您无需通过 User.objects.get(user = User.objects.get(username = current_username))获取用户 相反,请使用request.user。

@login_required
def data(request, page, keyword,strEncode):
    current_user = request.user
    data_s = dosomething() 
    UserRecord.objects.get_or_create(user=current_user,MyRecords=keyword) # in order to create unique value
    return JsonResponse(data_s, safe=False)
每次在 def数据视图中传递新关键字时, MyRecords = keyword 都会创建新记录,因此请查看您的代码。

答案 1 :(得分:0)

Mysql的

class UserRecord(models.Model):
    user = models.ForeignKey(User)
    MyRecords = models.CharField(max_length=128)
    class Meta:
        unique_together = (("user", "MyRecords"),) #mutil column uique idex
    def __unicode__(self):
        return self.user.username