Django mysql表名没有验证

时间:2013-05-11 16:31:18

标签: python mysql django orm mysql-python

我向Django app模型添加了类来创建mysql表。我在'歌曲'表中有'下载'表和'下载'列。

当我想同步db时,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 models

class 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 个答案:

答案 0 :(得分:1)

Django允许你make queries that span relationships

在您的情况下,从downloadssongs的外键意味着您通常可以根据关系从歌曲到下载进行查询:

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)

另外,我建议您将模型重命名为SingerSongDownload(大写,单数而不是复数),以遵循Django惯例。