--Confirming how to write many-to-one foreign key constraints in Django --Displaying foreign key constraints on the Django admin site
It is assumed that the status of the Task model object is described in the Status model. (Describe a many-to-one relationship between the Task model and the Status model)
Write the status model class as you normally would.
models/status.py
"""
Model for status
"""
from django.db import models
class Status(models.Model):
"""
Status for Task
"""
name = models.CharField('status', max_length=30, blank=False)
Describe foreign key constraints on the task class side
models/task.py
from django.db import models
from datetime import datetime
from webui.models.status import Status
class Task(models.Model):
"""
Task to do.
"""
name = models.CharField('Task name', max_length=30, blank=False)
startTime = models.DateTimeField('Start time', blank=True)
endTime = models.DateTimeField('End time', blank=True, null=True)
memo = models.CharField('Note', max_length=200, blank=True)
# status = models.CharField('Status', max_length=20, default='not started yet', blank=False)
status = models.ForeignKey(Status)
status = models.ForeignKey(Status)
This part describes the many-to-one relationship between the Task model and the Status model. ** This completes the description of the foreign key constraint **
Find another way to display arbitrary fields on the admin site. (Will you write it soon?)
Even if the Task object is set, the status item is "Status object", which is sad, so fix this.
models/status.py
from django.db import models
class Status(models.Model):
"""
Status for Task
"""
name = models.CharField('status', max_length=30, blank=False)
def __str__(self):
return self.name
def __str__(self):
return self.name
In this part, you can define which information is displayed as the information of the management site. (It just defines what is displayed when the object is called as a character string with str ??)
By modifying the Status model class When the Task model object is displayed from the management site The display is as expected.
Recommended Posts