如何使字段與相關模型的字段相關。我有兩個模型:專輯和照片,專輯模型有布爾字段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', ]
你就不能添加取決於專輯的私人領域的財產? –