我有两个模型,我想得到 - 模型1的一些字段到模型2.我正在使用
field in model 2 = models.ForeignKey(model1, to_field = 'field i want from model 1')
我在控制台中收到的错误是
myapp.IFileTable.calendar_year: (fields.E304) Reverse accessor for 'IFileTable.calendar_year' clashes with reverse accessor for 'IFileTable.created_on'.
HINT: Add or change a related_name argument to the definition for 'IFileTable.calendar_year' or 'IFileTable.created_on'.
lfcalendar.IFileTable.title: (fields.E311) 'IFile.title' must set unique=True because it is referenced by a foreign key.
我的模特1
class IFile(models.Model):
title = models.CharField(max_length=255, blank=True)
year = models.CharField(max_length=4)
uploaded_at = models.DateTimeField(auto_now_add=True)
我的模特2
class IFileTable(models.Model):
title = models.ForeignKey(IntermediateFile, to_field = 'title')
user = models.CharField(max_length = 10)
created_on = models.ForeignKey(IntermediateFile, to_field = 'uploaded_at')
calendar_year = models.ForeignKey(IntermediateFile, to_field = 'year')
答案 0 :(得分:2)
我认为你误解了外键的作用。它们允许您访问相关模型的整个实例,而不是单个字段。除非您希望它们指向不同的实例,否则没有理由让两个或三个FK指向同一个模型,但即使这样,您也不需要使用不同的to_field值。
你的模特应该是:
class IFileTable(models.Model):
intermediate_file = models.ForeignKey(IntermediateFile)
现在,给定IFileTable
的实例,你可以这样做:
my_ifiletable.intermediate_file.title
my_ifiletable.intermediate_file.year
my_ifiletable.intermediate_file.uploaded_at