2

所以我有两个模型;第一个用于帖子和第二张照片。每个帖子可以有很多照片。&我不确定如何在 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')

我怎样才能建立适当的关系,我怎样才能访问模板中的帖子和每张照片?

4

1 回答 1

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

模板:

{% for photo in post.photo_set %}
    {{ photo }}
{% endfor %}
于 2013-07-30T00:11:50.003 回答