2013-06-24 4 views
2

그래서 두 모델이 있습니다. 첫 번째는 게시물과 두 번째 사진입니다. 각 게시물에는 사진이 여러 개있을 수 있습니다. & 장고에서 일대 다 관계가 어떻게 구성되는지 확신 할 수 없습니다. Heres는장고 모델 1 : 게시물과 사진 사이의 많은 관계

내 모델 :

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

단지'photos'이이기 때문에 관계의 이름은'Post' 객체에 나타납니다. 나머지 질문 : * 무엇을 시도 했습니까? * – Hamish

+0

@Ramish와 수정 된 관계 이름 : {{post.postPhotos.0.title}}과 같은 것을 시도했습니다. 내가 잘못 생각한 것입니까? – Callum

+2

@CallumBonnyman'{{post.postPhotos.all.0.title}}'또는 {post.postPhotos.all %의 사진 %} {{photo.title}} {% endfor %}' – Ngenator

답변

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 

템플릿 : 그것은`postPhotos`했다 경우, 또는`related_name`이 더 정확한 것 있지만이 그대로 작동합니다

{% for photo in post.photo_set %} 
    {{ photo }} 
{% endfor %}