我正在尝试在Django中创建一个简单的待办应用。我很难理解外键的概念。每个项目都假设要获得多个公寓,每个公寓应获得多个任务。
型号:
# Project model
class Project(models.Model):
name = models.CharField(_("Name"), max_length=30)
city = models.CharField(_("City"), max_length=30)
street = models.CharField(_("Street"), max_length=30)
number = models.IntegerField(_("Number"), max_length=4)
ZIP = models.ImageField(_("ZIP"), max_length=10)
manager = models.CharField(_("Manager"), choices=managers, default='ariel')
# Apartments
apartment = models.ForeignKey(_("Apartment"), Apartment, on_delete=models.CASCADE)
def __repr__(self):
return "{}".format(self.name)
# Apartment model
class Apartment(models.Model):
building = models.CharField(_("Building"), max_length=4)
floor = models.CharField(_("Floor"), max_length=4)
number = models.CharField(_("Number"), max_length=4)
type = models.CharField(_("Type"), max_length=4)
upgraded = models.BooleanField(_("Upgraded"), default=False)
drawing = models.FileField(_("Drawing"), upload_to=None)
notes = models.TextField(_("Notes"), max_length=500)
status = models.BooleanField(_("Completed"), default=False)
# Tasks
airTunnels = models.ForeignKey(_("Air Tunnels"), Task, on_delete=models.CASCADE)
gasPipelines = models.ForeignKey(_("Gas Pipelines"), Task, on_delete=models.CASCADE)
def __repr__(self):
return "{} - {}".format(self.number, self.status)
# Task model
class Task(models.Model):
title = models.CharField(_("Task"), max_length=30)
doneBy = models.CharField(_("Done By"), choices=workers, default='daniel')
date = models.DateTimeField(_("Date"), default=timezone.now())
def __repr__(self):
return "{}".format(self.title)
[如果使用apartment = models.ForeignKey(_("Apartment"), Apartment, on_delete=models.CASCADE)
,则表示每个项目都有一个公寓。因此,您必须为每个公寓定义不同的项目。如果每个公寓只能有一个项目,则必须在公寓模型内定义外键,如下所示:
class Apartment(models.Model):
#...your other fields
project = models.ForeignKey(Project, on_delete=models.CASCADE)
对于公寓任务,如果我理解正确,您的公寓模型可以有多个任务。因此,您可以为此使用ManyToMany字段。有了此定义,每个公寓可以有多个任务。但是您的每个任务可以属于多个单元对象。如果您不希望每个任务都可以属于不同的单元对象,则必须设置OneToMany关系。可以通过向任务模型中添加foreignkeyfield来做到这一点:
class Task(models.Model):
#...your other fields
apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE)