[Fixed]-Django models create data duplicate

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

1👍

You don’t need to get user by User.objects.get(user=User.objects.get(username=current_username))
Instead use request.user for same.

@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)

And MyRecords=keyword will create a new record every time a new keyword is passed in the def data view, so please review your code.

Leave a comment