汽车系统表模型

'''
2、完成汽车系统表模型的建立(表关系自己设计)
	汽车表、汽车商家表、赞助商表、赞助商详情表

3、完成汽车系统的接口编写
	汽车表:八大接口(不需要写put方法)
	汽车商家表:八大接口(不需要写put方法)
'''
from django.db import models

# 汽车表、汽车商家表、赞助商表、赞助商详情表
class BaseModel(models.Model):
    is_delete = models.BooleanField(default=False)
    createdTime = models.DateTimeField(auto_now_add=True)
    class Meta:
        abstract = True

class Car(BaseModel):
    name = models.CharField(max_length=64)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    brand = models.ForeignKey(to='Brand', db_constraint=False, null=True, on_delete=models.SET_NULL, related_name='cars')
    sponsors = models.ManyToManyField(to='Sponsor', db_constraint=False, related_name='cars')

    @property
    def brand_name(self):
        return self.brand.name

    @property
    def sponsor_list(self):
        sponsor_list_temp = []
        for sponsor in self.sponsors.all():
            sponsor_dic = {
                'name': sponsor.name
            }
            try:
                sponsor_dic['phone'] = sponsor.detail.phone
            except:
                sponsor_dic['phone'] = '未知'
            sponsor_list_temp.append(sponsor_dic)
        return sponsor_list_temp

    class Meta:
        verbose_name_plural = '汽车'

    def __str__(self):
        return self.name

class Brand(BaseModel):
    name = models.CharField(max_length=64)

    class Meta:
        verbose_name_plural = '品牌'

    def __str__(self):
        return self.name

class Sponsor(BaseModel):
    name = models.CharField(max_length=64)

    @property
    def phone(self):
        try:
            return self.detail.phone
        except:
            return "无"

    class Meta:
        verbose_name_plural = '赞助商'

    def __str__(self):
        return self.name

class SponsorDetail(BaseModel):
    phone = models.CharField(max_length=11)
    sponsor = models.OneToOneField(to=Sponsor, db_constraint=False, on_delete=models.CASCADE, related_name='detail')

    class Meta:
        verbose_name_plural = '赞助商详情'

    def __str__(self):
        try:  # 连表可能会出现问题,所以要异常处理
            return self.sponsor.name + '的详情'
        except:
            return super().__str__()
posted @ 2019-12-30 17:01  simple123  阅读(184)  评论(0编辑  收藏  举报