2016-11-03 108 views
0

如何使字段與相關模型的字段相關。我有兩個模型:專輯和照片,專輯模型有布爾字段private。如何在照片中創建字段private,如果專輯字段等於無,則該值將具有False值,如果不是,則專輯專用字段的值將爲False相關對象字段的相關字段Django

models.py:

from django.db import models 
from django.contrib.auth.models import User 
import os 
import uuid 

def get_image_path(instance, filename): 
    return '{}.{}'.format(uuid.uuid4(), filename.split('.')[-1]) 


class Album(models.Model): 
    user = models.ForeignKey(User, related_name='albums', on_delete=models.CASCADE) 
    title = models.CharField(max_length=80, default='New album') 
    creation_date = models.DateField(auto_now_add=True) 
    private = models.BooleanField(default=False) 

    def __str__(self): 
     return self.title 

    class Meta: 
     ordering = ['-creation_date', ] 

class Photo(models.Model): 
    user = models.ForeignKey(User, related_name='photos', on_delete=models.CASCADE) 
    album = models.ForeignKey(Album, related_name='photos', on_delete=models.CASCADE, null=True, blank=True) 
    title = models.CharField(max_length=80, default='New photo') 
    image = models.ImageField(title, upload_to=get_image_path) 
    creation_date = models.DateField(auto_now_add=True) 
    # ??? 
    private = models.BooleanField() 
    # ??? 

    def __str__(self): 
     return self.title 

    class Meta: 
     ordering = ['-creation_date', ] 
+1

你就不能添加取決於專輯的私人領域的財產? –

回答

0

正如@RodXavier說只是使用屬性

class Photo(models.Model): 
    user = models.ForeignKey(User, related_name='photos', on_delete=models.CASCADE) 
    album = models.ForeignKey(Album, related_name='photos', on_delete=models.CASCADE, null=True, blank=True) 
    title = models.CharField(max_length=80, default='New photo') 
    image = models.ImageField(title, upload_to=get_image_path) 
    creation_date = models.DateField(auto_now_add=True) 

    @property 
    def private(self): 
     return getattr(self, 'album', False) 
+0

但我不能使用這種方法的過濾器。 – Rodion

+0

@Robin是的。你不能。有一種解決方案可以用於查找和過濾,在你的問題中你沒有提到,這是一個解決你問的問題 –