zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

[Django] Creating an app, models and database

DatabasedjangoApp and an Models creating
2023-09-14 09:00:52 时间

To add a new app, first cd to the project.

Then run:

python manage.py startapp scrumboard

After that a new folder call 'scrumboard' will be created in you applicaiton folder.

 

Now cd to scrumboard folder and open models.py:

from django.db import models
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class List(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return "List {}".format(self.name)


@python_2_unicode_compatible
class Card(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True)

    def __str__(self):
        return "Card {}".format(self.title)

 

Add a database:

python manage.py makemigrations

It check whether there is anything changed in my models.py file.

And you can see there is a new file generated inside 'migrations folder' called 0001_initial.py.

 

Now let's do migrations:

python manage.py migrate

 

If we did any changes in models.py, we need to run mirgration again:

from django.db import models
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class List(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return "List {}".format(self.name)


@python_2_unicode_compatible
class Card(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    list = models.ForeignKey(List, related_name="cards")
    story_points = models.IntegerField(null=True, blank=True)
    business_value = models.IntegerField(null=True, blank=True)

    def __str__(self):
        return "Card {}".format(self.title)

 

More docs for Model: https://docs.djangoproject.com/en/1.9/topics/db/models/