0

1.Models's name is UserRecord.
2.Below is the code of my view.

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

Requested below URL several times with no interval,something like concurrent threading .
http://127.0.0.1:8000/data/1/test/english/
After this operation done,MyRecords column is populated by duplicate values.
I found something in Django document to use 'with transaction.atomic' to deal with this problem but it did not work.

1
  • user = models.ForeignKey(User) Commented Nov 9, 2016 at 0:51

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

<blink>class UserRecord(models.Model): user = models.ForeignKey(User) MyRecords = models.CharField(max_length=128) def __unicode__(self): return self.user.username </blink>
@blueboy read your code carefully. The problem is in code you did not share.
user = models.ForeignKey(User),i mean no repeat records for current user.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.