【发布时间】:2017-03-18 09:05:17
【问题描述】:
我想为多对多关系添加额外的字段,并创建了一个名为 Contact 的中间模型(目标是实现一个允许用户关注其他用户并也被关注的系统)。
class Contact(models.Model):
user_from = models.ForeignKey(User,
related_name='rel_from_set')
user_to = models.ForeignKey(User,
related_name='rel_to_set')
created = models.DateTimeField(auto_now_add=True,
db_index=True)
class Meta:
ordering = ('-created',)
def __str__(self):
return '{} follows {}'.format(self.user_from, self.user_to)
我正在使用 Django 提供的用户模型(来自 django.contrib.auth.models)。由于这个模型不是我创建的,如果我想向它添加字段,我应该(或者至少,我认为我应该)动态地添加它们(使用猴子补丁)。所以在models.py文件的最后我添加了以下代码:
User.add_to_class('following', models.ManyToManyField('self', through=Contact , related_name='followers', symmetrical=False))
但是我运行了python manage.py makemigrations,我得到了以下错误:
Migrations for 'auth':
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem
ent\__init__.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem
ent\__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem
ent\base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem
ent\base.py", line 345, in execute
output = self.handle(*args, **options)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem
ent\commands\makemigrations.py", line 192, in handle
self.write_migration_files(changes)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem
ent\commands\makemigrations.py", line 210, in write_migration_files
migration_string = os.path.relpath(writer.path)
File "C:\Program Files (x86)\Python35-32\lib\ntpath.py", line 574, in relpath
path_drive, start_drive))
ValueError: path is on mount 'C:', start on mount 'D:'
经过谷歌快速搜索:
"os.relpath 确实为您提供了两个目录之间的相对路径。
您遇到的问题是,在 Windows 上,如果两个目录位于不同的驱动器上,则甚至不存在相对路径(这正是错误消息所说的)。 "
但是解决方案是什么? 我正在使用 Windows 8 和 Django 1.10。
【问题讨论】:
-
是什么让您认为该错误与添加的字段有关?在任何情况下,您都应该显示完整的回溯。
-
@DanielRoseman 已发布完整追溯。错误发生在我添加上面的代码之后,所以我很肯定这就是问题所在。
标签: python django windows path