我有两张桌子
表1
CREATE TABLE `profiles` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`first_name` varchar(45) DEFAULT NULL,
`surname` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`unique_id` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
表2
CREATE TABLE `bible_photo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`file` varchar(100) NOT NULL,
`file_name` varchar(45) DEFAULT NULL,
`unique_id` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
两个相应的模型
模型
class TProfiles(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
first_name = models.CharField(max_length=45, blank=True)
surname = models.CharField(max_length=45, blank=True)
email = models.CharField(max_length=45, blank=True)
unique_id = models.CharField(max_length=100, blank=True)
class Meta:
managed = False
db_table = 'profiles'
class Photo( models.Model ):
file = models.FileField( upload_to = settings.MEDIA_ROOT )
file_name = models.CharField(max_length=45, blank=True)
unique_id = models.CharField(max_length=100, blank=True)
def extension(self):
name, extension = os.path.splitext(self.file.name)
return extension
我想根据他们共享的唯一ID访问所有配置文件及其相应的个人资料图片。我在views.py文件中有以下内容。但是,虽然我可以单独访问它们,但我无法将它们组合起来传递给模板。
views.py
def register(request):
photos = Photo.objects.all
profiles = TProfiles.objects.all
return render_to_response("register.html", {
"form": form, "photos": photos,
}, RequestContext(request))
更新
我尝试将profile = models.ForeignKey(TProfiles)
添加到我的Photo模型中,但我一直抱怨缺少与“个人档案”表相关的列。当然,我不必将它们复制到照片表中?
OperationalError at /register/
(1054, "Unknown column 'bible_photo.profile_id' in 'field list'")
这是我模板中的代码行,它正在抱怨。我想看看我是否可以从照片中访问个人资料。
{% for p in photos %}
<h1>{{ p.profile }}</h1>
{% endfor %}
答案 0 :(得分:1)
像这样更改models.py
:
class TProfiles(models.Model):
first_name = models.CharField(max_length=45, blank=True)
surname = models.CharField(max_length=45, blank=True)
email = models.CharField(max_length=45, blank=True)
unique_id = models.CharField(max_length=100, blank=True)
class Meta:
managed = False
db_table = 'profiles'
class Photo( models.Model ):
file = models.FileField( upload_to = settings.MEDIA_ROOT )
file_name = models.CharField(max_length=45, blank=True)
unique_id = models.CharField(max_length=100, blank=True)
event_location_time = models.ForeignKey(TProfiles)
def extension(self):
name, extension = os.path.splitext(self.file.name)
return extension
然后改变你的view
:
def register(request):
profiles = TProfiles.objects.all()
return render_to_response("register.html", {
"form": form, "profiles": profiles,
}, RequestContext(request))
在您的template
中,您可以使用:
{% for profile in profiles %}
#access to profile object
{% for photo in profile.photo_set.all %}
#access to each profile photo object
{% endfor %}
{% endfor %}