我将类添加到Django应用程序模型中以创建mysql表。我有“下载”表,在“歌曲”表中有“下载”列。当我想同步数据库时,Django向我返回错误:CommandError: One or more models did not validate:mp3mid.downloads: Reverse query name for field 'song' clashes with field 'songs.downloads'. Add a related_name argument to the definition for 'song'.为什么不可能给表和列起相同的名字?这是我的models.py:from django_evolution.mutations import *from django.db import modelsclass singers(models.Model): name = models.CharField(max_length = 255) category = models.ForeignKey(categories)class songs(models.Model): name = models.CharField(max_length = 255) singer = models.ForeignKey(singers) downloads = models.IntegerField(max_length = 11) exclusive = models.BooleanField(default = 0) hit = models.BooleanField(default = 0) date = models.DateTimeField(auto_now_add = True) link = models.CharField(max_length = 255)class downloads(models.Model): song = models.ForeignKey(songs) date = models.DateTimeField(auto_now_add = True)
1 回答
GCT1015
TA贡献1827条经验 获得超4个赞
Django允许您进行跨关系的查询。
在您的情况下,从downloads到的外键songs意味着您通常可以按照从歌曲到下载的反向关系进行查询:
from datetime import datetime
# fetch all songs with a download with a date on or after 2013-05-01.
songs = song.objects.filter(downloads__date__gte=datetime(2013,5,1))
但是,在这种情况下您不能这样做,因为downloads与您的songs.downloads字段发生冲突。
您有两种选择。首先,您可以related_name根据错误消息的建议设置外键。
class downloads(models.Model):
song = models.ForeignKey(songs, related_name="related_downloads")
或者,您可以重命名您的song.downloads字段。
class songs(models.Model):
...
num_downloads = models.IntegerField(max_length = 11)
顺便说一句,我建议你重命名你的模型Singer,Song和Download(大写,单数而不是复数),遵循Django的约定。
添加回答
举报
0/150
提交
取消