[PYTHON] Django Foreign Key Tutorial Ends in 10 Minutes

2020-04-01 Created: windows10 / Python-3.8.2-amd64 / Django-3.0.4

There isn't much information in Japanese about Django's foreign keys online either. But usually, "favorite food" and "address book" should be different apps, I think that how to use foreign keys is a basic compulsory item.

For foreign keys in the same database and to foreign databases I have created a simple tutorial. For those who want to easily know how to correlate multiple databases with each other.

--Cat management app cafe for cat cafes --Create a table with the name of the cat and a table with your favorite food, and associate them with a foreign key. --Cat address book app negura --Create a database of cats. Called by a foreign key from the cafe app.

If you're new to Django, read the basic tutorial first. Practical tutorial on Django in 10 minutes

Preparation

Creating a project

Create a new project by executing the following in the place where you want to put the source.

django-admin startproject mysite

Enter the created directory mysite and create two new applications.

cd mysite
python manage.py startapp cafe
python manage.py startapp sumika

The arrangement of the files so far is like this

mysite/
    mysite/
        __pycashe__/    <-do not worry about
        setting.py, urls.py etc.*.5 py
    neko/
        migrations/     <-do not worry about
        models.py, views.py etc.*.6 py
    sumika/
        migrations/     <-do not worry about
        models.py, views.py etc.*.6 py
    manage.py  

Registration of apps that make up the project

Register two apps, cafe and negura.

mysite/mysite/settings.py


INSTALLED_APPS = [
    'cafe.apps.CafeConfig',
    'negura.apps.NeguraConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

mysite/mysite/urls.py


from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('cafe/', include('cafe.urls')),
    path('negura/', include('negura.urls')),
    path('admin/', admin.site.urls),
]

App implementation

Creating a cafe app

Creating models, views and urls

neko_food is a foreign key in the same database in the cafe app neko_negura is a foreign key to the negura app, that is, another database of the next app.

The def __str__ (self): method is usually needed in django's generic views when using ForeignKey. If you do not override this method, it will appear in your browser The instance name is displayed as food_name.object (1) instead of sanma. Thanks to this method, the string is displayed in the pull-down list when using CreateView or FormView.

neko_negura is pulling the model from an outside app, so Call the model after prefixing the app name with negura.NeguraModel.

mysite/cafe/models.py


from django.db import models
from negura.models import NeguraModel

class NekoModel(models.Model):
    neko_name = models.CharField(max_length = 20)
    neko_food = models.ForeignKey('FoodModel', null = True,on_delete = models.SET_NULL)
    neko_negura = models.ForeignKey('negura.NeguraModel', null = True,on_delete = models.SET_NULL)


class FoodModel(models.Model):
    food_name = models.CharField(max_length = 20)
    def __str__(self):
        return self.food_name

Don't get confused about which view uses which template It has a terrible file name.

mysite/cafe/views.py


from django.views import generic
from .models import NekoModel, FoodModel

class NekoListView(generic.ListView):
    model = NekoModel
    context_object_name = 'nekolistview_context'
    template_name = 'cafe/nekolistview_template.html'

class NekoCreateView(generic.CreateView):
    model = NekoModel
    context_object_name = 'nekocreateview_context'
    template_name = 'cafe/nekocreateview_template.html'
    fields = ['neko_name', 'neko_food', 'neko_negura']
    success_url = '/cafe/nekolist_url'

class FoodListView(generic.ListView):
    model = FoodModel
    context_object_name = 'foodlistview_context'
    template_name = 'cafe/foodlistview_template.html'

urls.py creates a new file I've given it a crappy name so I don't get confused about which pathname points to which view.

mysite/cafe/urls.py


from django.urls import path
from . import views

urlpatterns = [
    path('nekolist_url', views.NekoListView.as_view(), name = 'nekolistview_path'),
    path('nekocreate_url', views.NekoCreateView.as_view(), name = 'nekocreateview_path'),
    path('foodlist_url', views.FoodListView.as_view(), name = 'foodlistview_path'),
]

I will not create a view for entering food and address because it will take a lot of tutorial work. Edit and enable admin.py for input from the admin screen instead.

mysite/cafe/admin.py


from cafe.models import NekoModel, FoodModel
from django.contrib import admin

admin.site.register(NekoModel)
admin.site.register(FoodModel)

Creating a template

Create 3 templates. I put it in the default directory, but I don't really like it because the hierarchy is too deep.

mysite/cafe/template/cafe/nekolistview_template.html


<h1>Ichiran the cat</h1>
 <table>
  {% for neko_param in nekolistview_context %}
    <tr>
      <td>{{ neko_param.neko_name }}</td>
      <td>{{ neko_param.neko_food.food_name }}</td>
      <td>{{ neko_param.neko_negura.negura_name }}</td>
    </tr>
  {% endfor %}
</table>
<p><a href = "{% url 'foodlistview_path' %}">Cat food</a></p>
<p><a href = "{% url 'neguralistview_path' %}">Cat roost</a></p>
<p><a href = "{% url 'nekocreateview_path' %}">Cat</a></p>

mysite/cafe/template/cafe/foodlistview_template.html


<h1>Cat food</h1>
<table>
  {% for food_param in foodlistview_context %}
    <tr>
      <td>{{ food_param.food_name }}</td>
    </tr>
  {% endfor %}
</table>
<p><a href = "{% url 'nekolistview_path' %}">Ichiran the cat</a></p>

mysite/cafe/template/cafe/nekocreateview.html


<h1>Cat</h1>
<form method = "post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type = "submit" value = "Toro" />
</form>
<p><a href = "{% url 'nekolistview_path' %}">Ichiran the cat</a></p>

Creating a negura app

Creating models, views and urls

Basically, it's a repetition of what I did at the cafe.

mysite/negura/models.py


from django.db import models

class NeguraModel(models.Model):
    negura_name = models.CharField(max_length = 20)
    def __str__(self):
        return self.negura_name

mysite/negura/views.py


from django.views import generic
from .models import NeguraModel

class NeguraListView(generic.ListView):
    model = NeguraModel
    context_object_name = 'neguralistview_context'
    template_name = 'negura/neguralistview_template.html'

mysite/negura/urls.py


from django.urls import path
from . import views

urlpatterns = [
    path('neguralist_url', views.NeguraListView.as_view(), name = 'neguralistview_path'),
]

mysite/negura/admin.py


from cafe.models import NeguraModel
from django.contrib import admin

admin.site.register(NeguraModel)

Creating a template

Create one template The location is the default location.

mysite/negura/template/negura/neguralistview_template.html


<h1>Cat roost</h1>
<table>
  {% for negura_param in neguralistview_context %}
    <tr>
      <td>{{ negura_param.negura_name }}</td>
    </tr>
  {% endfor %}
</table>
<p><a href = "{% url 'nekolistview_path' %}">Ichiran the cat</a></p>

Finish

Migration and admin settings

After migrating, create an administrator for the admin site and Make the admin screen accessible.

python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

Start HTTP server and enter initial data

Start the development server. The port number is 8000 because it is started by default.

python manage.py runserver

Access the following with a browser to display the admin screen. "Eat" and "Sumika" cannot be entered directly with this app, so enter them from the admin screen.

http://localhost:8000/admin/

For example, food is "Saury" and "Crispy", and Sumika is "Danboru" and "Moufu".

Operation check

Enter the following to get a list of cats. At first, there are no registered cats, so they are not on the table.

http://localhost:8000/neko/

When you enter the registration screen from the "Cat Touroku" link, Enter the cat's name in the form and "Food" and "Negura" can be selected from the drop-down list.

The end

Recommended Posts

Django Foreign Key Tutorial Ends in 10 Minutes
Write foreign key constraints in Django
Django Foreign Key on_delete argument
Foreign Key in Python SQLite [Note]
Deploy Django in 3 minutes using docker-compose
CSS environment created in 10 minutes using Django
Models in Django
Python Django Tutorial (5)
Python Django Tutorial (2)
django tutorial memo
Build a Django environment with Vagrant in 5 minutes
Python Django Tutorial (8)
Python Django Tutorial (6)
Start Django Tutorial 1
Python Django Tutorial (7)
Python Django Tutorial (1)
Python Django tutorial tutorial
Forms in Django
Python Django Tutorial (3)
Python Django Tutorial (4)
Key input in Python
Python Django tutorial summary
Learn Pandas in 10 minutes
Django Polymorphic Associations Tutorial
Django 1.4.2 session key generation
django oscar simple tutorial
Model changes in Django
Understand in 10 minutes Selenium
Selenium running in 15 minutes
Django Girls Tutorial Note
Key input in Python