Django Fixture文件中model字段应指向何处?加载失败求助
Django JSON Fixture加载失败问题排查与解决
我尝试用JSON fixture填充Movie模型,但不确定其中的model字段应指向什么。我认为它应该指向模型所在位置,但加载文件时始终报错:Problem installing fixture '/workspace/django-film-club/film/fixtures/films.json'。
相关代码
film/fixtures/films.json
[ { "model": "film.movie", "pk": null, "fields": { "title": "Django Unchained", "slug": "django-unchained", "year": 2012, "genre": "WESTERN", "synopsis": "<p>With the help of a German bounty-hunter, a freed slave sets out to rescue his wife from a brutal plantation owner in Mississippi.<p>", "director": "Quentin Tarantino", "excerpt": "A freed slave sets out to rescue his wife from a brutal plantation owner in Mississippi.", "added_on": "2024-06-01T09:43:19.754Z" } }, ]
film/models.py
class Movie(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) year = models.IntegerField(('year'), default=datetime.datetime.now().year) genre = models.CharField(max_length=15, choices=GENRE_CHOICES, default='horror') synopsis = models.TextField() director = models.CharField(max_length=200, unique=True) excerpt = models.TextField(blank=True) added_on = models.DateTimeField(auto_now_add=True)
问题排查与解决步骤
- 确认
model字段格式:你写的"model": "film.movie"是正确的,格式为[app标签].[模型类名小写],这里app是film,模型类Movie小写后为movie,这部分没问题。 - 修复JSON语法错误:JSON数组最后一个对象末尾多了逗号(
},]),这会导致解析失败。修改后移除该逗号:[ { "model": "film.movie", "pk": null, "fields": { "title": "Django Unchained", "slug": "django-unchained", "year": 2012, "genre": "WESTERN", "synopsis": "<p>With the help of a German bounty-hunter, a freed slave sets out to rescue his wife from a brutal plantation owner in Mississippi.<p>", "director": "Quentin Tarantino", "excerpt": "A freed slave sets out to rescue his wife from a brutal plantation owner in Mississippi.", "added_on": "2024-06-01T09:43:19.754Z" } } ] - 匹配
genre选项值:检查GENRE_CHOICES定义,确保"WESTERN"是其中的有效值(注意大小写一致),如果选项是小写'western',则需要同步修改fixture中的值。 - 移除自动生成字段的手动赋值:
added_on设置了auto_now_add=True,会自动生成时间,建议从fixture的fields中删除该字段,避免冲突。 - 检查唯一性约束:
title、slug、director都有unique=True,确保fixture中的值在数据库中无重复,否则会触发唯一性错误。 - 查看详细错误日志:加载时添加
--verbosity 2参数获取详细报错,精准定位问题:python manage.py loaddata film/fixtures/films.json --verbosity 2
内容的提问来源于stack exchange,提问作者Mus Ali
相关产品推荐
相关产品推荐

