创建带有外键的对象

时间:2020-06-22 08:42:30

标签: django sqlite django-models django-admin

每当我尝试在下面的代码中运行“ add_rat”时,我都会收到错误消息

    Exception Value:    
Cannot assign "441": "Myrating.movieId" must be a "Movie" instance.

我尝试将其作为movieId_id = movieId传递给给出错误的函数定义bu:

FOREIGN KEY constraint failed

我还尝试将其作为int()值传递,但是它不起作用。

我想创建具有2个外键的Myrating对象。

admin.py:

from django.contrib import admin
from .models import Movie,Myrating
from django.contrib.auth.models import User
import csv


# Register your models here.
def add_set(modeladmin, request,queryset):
    with open('./movies.csv','r',encoding='utf-8', errors='ignore') as _filehandler:
        csv_file_reader=csv.DictReader(_filehandler)
        for row in csv_file_reader:
            movie=Movie.objects.create_movie(row['movieId'],row['title'],row['genres'],"mov.jpg")
add_set.short_description = "New_Day"
def add_rat(modeladmin, request,queryset):
    with open('./ratings.csv','r',encoding='utf-8', errors='ignore') as _filehandler:
        csv_file_reader=csv.DictReader(_filehandler)
        for row in csv_file_reader:
            movie=Myrating.objects.create_movie(int(row['userId']),Movie.objects.get(movieId=row['movieId']),float(row['rating']))
add_rat.short_description = "New_rat"
def add_user(modeladmin,request,queryset):
    i=1
    while i<=7045:
        user = User.objects.create_user(i, '', 'password')
        user.save()
        i+=1
add_user.short_description = "New_use"
class movie_admin(admin.ModelAdmin):
    list_display=('title','genre')
    list_filter=('genre','title')
    actions=[add_set,add_user,add_rat]
admin.site.register(Movie,movie_admin)
admin.site.register(Myrating)

models.py:

from django.contrib.auth.models import Permission, User
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
class movie_manager(models.Manager):
    def create_movie(self, movieId,title,genre,movie_logo):
        movie = self.create(movieId=movieId,title=title,genre=genre,movie_logo=movie_logo)
        # do something with the book
        return movie
class Movie(models.Model):
    movieId=models.PositiveIntegerField()
    title       = models.CharField(max_length=200)
    genre       = models.CharField(max_length=100)
    movie_logo  = models.FileField()
    objects=movie_manager()
    def __str__(self):
        return str(self.title)
class rating_manager(models.Manager):
    def create_movie(self, user,movieId,rating):
        movie = self.create(user_id=user,movieId=movieId.id,rating=rating)
        # do something with the book

        return movie
class Myrating(models.Model):

    user    = models.ForeignKey(User,on_delete=models.CASCADE)
    movieId= models.ForeignKey(Movie,on_delete=models.CASCADE)
    rating  = models.IntegerField(default=1,validators=[MaxValueValidator(5),MinValueValidator(0)])
    objects=rating_manager()

1 个答案:

答案 0 :(得分:0)

您具有引用到Movie模型的movieID,为此,在保存时,您需要提供应为Movie实例的值。

#turn off default settings mv ~/.m2/settings.xml ~/.m2/settings.xml.off #turn on again mv ~/.m2/settings.xml.off ~/.m2/settings.xml

此处movieID是Movie实例,但您分配的是一个int的movieID.id。 这就是为什么它会引发错误。

movie = self.create(user_id=user,movieId=movieId.id,rating=rating)

以下是解决方案。

Cannot assign "441": "Myrating.movieId" must be a "Movie" instance.

movie = self.create(user_id=user,movieId=movieId,rating=rating)

您可以将Myrating movieId 字段重命名为 movie ,因为电影名称是有意义的,因为它与电影实例相关。

有关更多详细信息和示例,请遵循官方文档link