用Django做一个简单的记账网站(三)定义数据模型
按前面的文章操作,已经能成功运行并显示简单的界面样式了,接下来需要定义数据模型。
因为是打算替代停运的网易有钱app,所以会参考从app中导出的历史数据。需要记录账户、收支大类、收支细目、金额、币种、时间、备注。如下所示:
时间 | 账户 | 大类 | 小类 | 金额 | 币种 | 备注 |
12/20/20 | 现金钱包 | 餐饮 | 工作餐 | 18 | 人民币 | 时代广场 |
12/22/20 | 支付宝 | 购物 | 数码 | 2999 | 人民币 | ipad 2020 |
于是分成货币、资金账户、类别、收支项,在accounting/models.py中定义:
from django.db import models
from django.utils import timezone
class Currency(models.Model):
name = models.CharField(max_length=100)
icon = models.CharField(max_length=100)
def __str__(self):
return self.name
class Meta:
ordering = ['id']
class Account(models.Model):
name = models.CharField(max_length=100)
amount = models.DecimalField(max_digits=8, decimal_places=2)
currency = models.ForeignKey(Currency, on_delete=models.SET_NULL, null=True, default=1)
icon = models.CharField(max_length=100, null=True)
created_date = models.DateTimeField(default=timezone.now)
updated_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
class Meta:
ordering = ['created_date']
class Category(models.Model):
CATEGORY_TYPES = (
("收入", "income"),
("支出", "expense")
)
name = models.CharField(max_length=100)
icon = models.CharField(max_length=100)
category_type = models.CharField(choices=CATEGORY_TYPES, default=CATEGORY_TYPES[0][1], max_length=100)
def __str__(self):
return self.name
class Meta:
ordering = ['id']
class SubCategory(models.Model):
name = models.CharField(max_length=100)
icon = models.CharField(max_length=100)
parent = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.name
class Meta:
ordering = ['id']
class HistoryRecord(models.Model):
account = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True, default=1)
time_of_occurrence = models.DateTimeField(default=timezone.now)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)
sub_category = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null=True, blank=True)
currency = models.ForeignKey(Currency, on_delete=models.SET_NULL, null=True, default=1)
amount = models.DecimalField(max_digits=8, decimal_places=2)
comment = models.CharField(max_length=500, null=True, blank=True)
created_date = models.DateTimeField(default=timezone.now)
updated_date = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ['-time_of_occurrence']
然后做数据迁移
python manage.py makemigrations
python manage.py migrate
此时进入mysql能看到产生了新的数据表,比如accounting_category.
由于在前端只想记录收支,于是打算利用django自带的admin后台管理,来增加大类、小类和账户,毕竟这几种是不会每天记录的,记录一次即可。
修改admin.py,在admin中注册对应的model
from django.contrib import admin
from .models import *
admin.site.register(Currency)
admin.site.register(Account)
admin.site.register(Category)
admin.site.register(SubCategory)
admin.site.register(HistoryRecord)
再进入后台便能看到可以编辑管理这几种model了。