字段涉及相关对象Django的字段

时间:2016-11-03 04:29:23

标签: django

如何制作与相关模型领域相关的字段。我有两个模型:专辑和照片,专辑模型有布尔字段private。如何在照片中创建字段private,如果相册字段等于无,则为False值,如果不是,则为专用字段的值。

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 :(得分: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)