我有一个显示游戏的应用程序,用户可以借用它们。我想将每个用户的借用游戏数量限制为最多 3 个游戏。我创建了两个模型借用和游戏。除了最大借用外,这些方法效果很好。
# Method display borrowed games
@login_required
def borrows(request):
borrows = Borrow.objects.filter(owner = request.user).order_by('date_borrowed')
context = {'borrows':borrows}
return render(request, 'gameapp/borrows.html', context)`
# Methos allow the user borrow single game
@login_required
def borrow(request, boardgame_id):
boardgame = Boardgame.objects.get(id=boardgame_id)
if request.method != 'POST':
form = BorrowForm()
else:
form = BorrowForm(data = request.POST)
if form.is_valid():
borrow_boardgame = form.save(commit = False)
borrow_boardgame.owner = request.user
# Replace the borrow varibale from borrow Model to main game
borrow_boardgame.borrow = boardgame
form.save()
return redirect('gameapp:borrows')
context = {'boardgame': boardgame, 'form':form}
return render(request, 'gameapp/borrow.html', context)
我也使用了 limit [:3] 但这将使用户继续向后端的数据库发送数据。
# A model for the game
class Boardgame(models.Model):
name = models.CharField(max_length=50)
date_added = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.name
# A model for borrowing a game
class Borrow(models.Model):
borrow = models.ForeignKey(Boardgame, on_delete=models.CASCADE)
date_borrowed = models.DateTimeField(auto_now_add=True)
date_returned = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE, default=3)
def __str__(self):
return str(self.borrow)```
你可以做一个
if
条件检查他是否在里面借了超过3场form.is_valid()
,像下面这样:
if form.is_valid():
borrowed_count = Borrow.objects.filter(owner=request.user).count()
if borrowed_count < 4:
form.save()
else:
print("You've borrowed 3 games already") # or whatever
此外,
default
在您的 owner
字段中指定的是 user.pk
而不是 games
,您应该更改它。