Created
April 9, 2019 02:55
-
-
Save Xifeng2009/07605b0fbbbb651937713cc3decdc90c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# In settings.py | |
DATABASES = { | |
'default': { | |
'ENGINE': 'django.db.backends.mysql', | |
'NAME': 'mysql', | |
'USER': 'root', | |
'PASSWORD': 'YOUR PASSWORD', | |
'HOST': '127.0.0.1', | |
'PORT': '3306', | |
} | |
} | |
# In app/models.py | |
from django.db import models | |
class Topic(models.Model): | |
title = models.CharField(max_length=50, null=True, blank=True, verbose_name='标题') | |
text = models.CharField(max_length=5000, null=True, blank=True) | |
date_added = models.DateTimeField(auto_now_add=True) | |
def __str__(self): | |
return self.title | |
# Run these code in terminal | |
# python3 manage.py makemigrations | |
# python3 manage.py migrate | |
# In admin.py | |
from django.contrib import admin | |
from .models import Topic | |
admin.site.register(Topic) | |
# In terminal | |
python3 manage.py createsuperuser | |
# Go admin page | |
http://127.0.0.1/admin/ | |
# In views.py | |
def base2(request): | |
objs = Topic.objects.all() | |
context = {'data': objs} | |
return render(request, 'examples/base2.html', context) | |
# In templates | |
<p>Examples of ORM</p> | |
<table> | |
<thead></thead> | |
<tbody> | |
<th>Title</th> | |
<th>Text</th> | |
<th>Date</th> | |
{% for obj in data %} | |
<tr> | |
<td>{{ obj.title }}</td> | |
<td>{{ obj.text }}</td> | |
<td>{{ obj.date_added }}</td> | |
</tr> | |
{% endfor %} | |
</tbody> | |
</table> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment