django 如何确保一个对象不会被添加两次

rjzwgtxy  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(111)

我想在观看列表中添加电影,这是电影型号

from django.db import models

# Create your models here.
from django.db import models
from django.contrib.auth.models import User

from Crew.models import *
# from Movies.models import Audience_Review
from Details.models import *
# Create your models here.
# Foreign keys are bookmarked

class Movie(models.Model):
    user=models.ForeignKey(User,on_delete=models.CASCADE,default=True)
    name=models.CharField(max_length=100,unique=True)
    slug=models.SlugField(max_length=100,unique=True,blank=True)
    year=models.CharField(max_length=5,blank=True)
    language=models.CharField(max_length=50,blank=True)
    release=models.CharField(max_length=100,blank=True)

    rating=models.CharField(max_length=20,blank=True)
    audience_score=models.CharField(max_length=20,blank=True,null=True)

    poster=models.ImageField(upload_to='movies/poster',blank=True)
    cover=models.ImageField(upload_to='movies/cover',null=True,blank=True)

    duration=models.CharField(max_length=50,default=None,blank=True)
    streaming=models.ForeignKey(Streaming,on_delete=models.CASCADE,blank=True,null=True)
    ott=models.TextField(max_length=50,blank=True,null=True)

    starring= models.ForeignKey(Actor,on_delete=models.CASCADE,related_name='actors',blank=True,null=True)
    actors=models.ManyToManyField(Actor,related_name='actor',blank=True)
    Characters=models.ManyToManyField(Character,related_name='character',blank=True)

    director=models.ForeignKey(Director,on_delete=models.CASCADE,blank=True,null=True)
    writers=models.ManyToManyField(Writer,related_name='writer',blank=True)
    cinematographer=models.ForeignKey(Cinematographer,on_delete=models.CASCADE,null=True,blank=True)

    based =models.CharField(max_length=100,blank=True,null=True)
    genres=models.ManyToManyField(Genre,blank=True)

    certification=models.ForeignKey(Certification,on_delete=models.CASCADE,null=True,blank=True)
    synopsis=models.TextField(max_length=1000,blank=True)
    trailer=models.CharField(max_length=500,blank=True)
    def __str__(self):
        return self.name

字符串
这是我的观看列表模型,电影被当作外键

from django.db import models
from django.contrib.auth.models import User
from Movies.models import Movie

# Create your models here.
class Watchlist(models.Model):
    user=models.ForeignKey(User,on_delete=models.CASCADE)
    movie=models.ForeignKey(Movie,on_delete=models.CASCADE)
    quantity=models.IntegerField(default=1)
    date=models.DateField(auto_now_add=True)
    def __str__(self):
        return self.movie.name


这是我用来将它添加到监视列表的URL:

href="{% url 'Watchlist:add_watchlist' mov.id %}"


这是路径

from django.urls import path
from Watchlist import views
app_name='Watchlist'
urlpatterns = [
    path('view_watchlist',views.view_watchlist,name='view_watchlist'),
    path('add_watchlist/<int:p>',views.add_watchlist,name='add_watchlist'),
    path('delete_watchlist/<int:p>',views.delete_watchlist,name='delete_watchlist')
]


这是视图。py

type herefrom django.shortcuts import render,redirect
from Movies.models import Movie
from Movies.views import *
from Watchlist.models import Watchlist
from django.contrib import messages
# from django.contrib.auth.decorators import login_required
# Create your views here.

def view_watchlist(request):
    user=request.user
    watchlist=Watchlist.objects.filter(user=user) #filter based on user
    return render(request,'watchlist.html',{'watchlist':watchlist})

def add_watchlist(request,p):
    user=request.user
    movie=Movie.objects.get(id=p)
    try:
        watchlist=Watchlist.objects.all()
        if movie not in watchlist:
            watchlist=Watchlist.objects.create(user=user,movie=movie)
            watchlist.save()
        else:
            pass
    finally:
        return view_watchlist(request)
    return render(request,'watchlist.html')

def delete_watchlist(request,p):
    user=request.user
    movie=Movie.objects.get(id=p)
    try:
        watchlist=Watchlist.objects.get(movie=movie,user=user)
        watchlist.delete()
    except:
        pass
    return redirect('Watchlist:view_watchlist')


当我点击添加到观看列表链接时,即使电影已经存在,它将再次添加,
我怎么才能确保它不会被添加两次,我应该为它做什么改变…。

gg0vcinb

gg0vcinb1#

更改add_watchlist函数,如下所示:

def add_watchlist(request,p):
    user=request.user
    movie=Movie.objects.get(id=p)
    try:
        watchlist=Watchlist.objects.filter(movie=movie)
        if not watchlist.exists():
            watchlist=Watchlist.objects.create(user=user,movie=movie)
            watchlist.save()
        else:
            pass
    finally:
        return view_watchlist(request)
    return render(request,'watchlist.html')

字符串
如果你想检查movie是否不存在特定的user,请在过滤器中添加user,如下所示:

watchlist=Watchlist.objects.filter(movie=movie, user=user)

相关问题