django外键相关对象未保存更改,无法编辑

kuuvgm7e  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(364)

我有两个模型,电影和评论。review有一个与电影相关的外键字段。我一直在尝试编辑与电影示例关联的审阅对象。
models.py

class Movie(models.Model):
    title = models.CharField(max_length=160)

class Review(models.Model):
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='reviews')
    author = models.CharField(max_length=150)
    active = models.BooleanField(default=True)

views.py


# Create and save movie object

    movie = Movie(title="Nightcrawler")
    movie.save()

    # Create and save two review objects
    review1 = Review(movie=movie, author="John", active=True)
    review2 = Review(movie=movie, author="Rob", active=False)
    review1.save()
    review2.save()

    print("Before: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.")

    active_reviews = movie.reviews.filter(active=True)

    print("There are " + str(len(active_reviews)) + " active reviews.")
    movie.reviews.set(active_reviews)
    movie.reviews.first().author = "Abby"

    # Try and save both objects just for good measure.
    # Not sure if it is necessary to do this. Does not
    # seem to work anyway
    movie.reviews.first().save()
    movie.save()

    print("After: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.")
    print("Author of the first review is: " + str(movie.reviews.first().author))

views.py代码的输出如下所示:

Before: Nightcrawler has 2 reviews.
There are 1 active reviews.
After: Nightcrawler has 2 reviews.
Author of the first review is: John

我希望并期待对所做的更改 movies.reviews 但输出显示 set() 方法或更改author值实际上会更改电影示例。为什么这些编辑都不被保留?
有趣的是 movies.reviews.first().delete() 似乎确实删除了第一次审查。我很好奇为什么这样做有效,而其他的改变却没有。
谢谢你抽出时间!

olhwl3o2

olhwl3o21#

我认为发生这种情况是因为在变量中没有捕捉到结果。
试试这个:

rv = movie.reviews.first() # catch the first one 

rv.author = "BLA" 

rv.save()
zpgglvta

zpgglvta2#

如果要操纵对象,应首先将其存储在变量中

movie = Movie(title="Nightcrawler")
    movie.save()

    # Create and save two review objects
    review1 = Review(movie=movie, author="John", active=True)
    review2 = Review(movie=movie, author="Rob", active=False)
    review1.save()
    review2.save()

    print("Before: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.")

    active_reviews = movie.reviews.filter(active=True)

    print("There are " + str(len(active_reviews)) + " active reviews.")
    movie.reviews.set(active_reviews)

    first_review = movie.reviews.first()
    first_review.author = "Abby"
    first_review.save()
    movie.save()

没有保存它,因为您更新的对象与您保存的对象不同,因为您通过调用运行了另一个查询 first() 再一次。

相关问题