所以我有两个型号;第一个是帖子和第二张照片。每个帖子都可以包含很多照片。 &安培;我不确定如何在django中构建一对多的关系。
继承我的模特:
class Post(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
pub_date = models.DateTimeField('date published')
class Photo(models.Model):
FILE_TYPE_CHOICES = (
('full', 'Full Width'),
('half', 'Half Width')
)
title = models.CharField(max_length=200)
description = models.TextField()
photoType = models.CharField(max_length=16,choices = FILE_TYPE_CHOICES, default = 'full', blank = True)
imageFile = models.ImageField(upload_to='uploaded')
containedPost = models.ForeignKey('Post', related_name='photoPosts')
我怎样才能建立正确的关系?我如何能够访问帖子&模板中的每张照片?
答案 0 :(得分:0)
模型:
class Post(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.title
class Photo(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
FILE_TYPES = (
('full', 'Full Width'),
('half', 'Half Width')
)
photo_type = models.CharField(max_length=4, choices=FILE_TYPES, default='full', blank=True)
imageFile = models.ImageField(upload_to='uploaded')
post = models.ForeignKey('Post')
def __unicode__(self):
return self.title
TEMPLATE:
{% for photo in post.photo_set %}
{{ photo }}
{% endfor %}