Table Relationships in Django
Use Cases for One-to-One Relationships
In QQ, basic user info is linked to detailed info—this saves query time.
One-to-one tables can be merged into one or split into two separate tables.
Foreign keys should be placed on the many side of a one-to-many relationship. Create base tables first before establishing foreign key constraints.
For many-to-many relationships, foreign keys are set in the intermediate table.
Creating Table Relasionships
# Define base model first
class Book(models.Model):
title = models.CharField(max_length=32)
price = models.DecimalField(max_digits=8, decimal_places=2)
publish = models.ForeignKey(to='Publish')
author = models.ManyToManyField(to='Author')
class Publish(models.Model):
title = models.CharField(max_length=32)
email = models.EmailField()
class Author(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField()
author_detail = models.OneToOneField(to='AuthorDetails')
class AuthorDetails(models.Model):
phone = models.BigIntegerField()
address = models.CharField(max_length=32)
Django Request Lifecycle
Named vs Unnamed Groups
Unnamed Groups
url(r'^test/([0-9]{4})/', views.test)
- Error: test() takes 1 positional argument but 2 were given
- When unnamed groups exist, matched content becomes positional arguments
test(request, x)
Named Groups
url(r'^test_add/(?P<y>\d+)/', views.test_add)
- When named groups exist, matched content becomes keyword arguments
test_add(request, y)
Additional Notes
- Both group types allow passing extra parameters to view functions
- Mixing group types in same pattern causes error
url(r'^index/(\d+)/(?P<y>\d+)/', views.index)fails- Only use one group type per pattern
Route Matching
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'test/', views.test),
url(r'test_add/', views.test_add),
]
Matching Behavior
- Django matches regex patterns sequentially
- If no slash is present, browser redirects with trailing slash
- Disable auto redirection via
APPEND_SLASH = False $restricts matching to exact suffix- Query parameters (
?) are ignored during matching
Reverse Resolution
What Is Reverse Resolution?
Generate URLs dynamically from named patterns.
Case 1: No Regex in Pattern
url(r'^home/', views.home, name='xxx')
Frontend:
<a href="{% url 'xxx' %}">111</a>
Backend:
def get_url(request):
url = reverse('xxx')
return redirect(url)
Case 2: Unnamed Group Resolution
Error when calling reverse('xxx') without arguments.
Frontend:
<a href="{% url 'xxx' 1 %}">111</a>
Backend:
reverse('xxx', args=(1,))
Case 3: Named Group Resolution
Frontend:
<a href="{% url 'xxx' yyy=1 %}">111</a>
Backend:
reverse('xxx', kwargs={'yyy': 1})
Practical Example: Edit Functionality
url(r'^edit_user/(\d+)/', views.edit_user, name='edit')
def edit_user(request, edit_id):
pass
Template usage:
{% for user_obj in user_list %}
<a href='/edit_user/{{user_obj.id}}/'>Edit</a>
<a href='{% url "edit" user_obj.id %}'>Edit</a>
{% endfor %}
URL Dispatching
Prerequisites
Each Django app can have its own urls.py, templates, and static directories.
This enables modular development and easy integration.
Main URL Configuration
from django.conf.urls import url, include
urlpatterns = [
url(r'^app01/', include('app01.urls')),
url(r'^app02/', include('app02.urls')),
]
Sub-URL Configuration
from django.conf.urls import url
from app01 import views
urlpatterns = [
url('^reg/', views.reg)
]
Namespaces
Purpose
Avoid naming conflicts between apps.
Usage
Front end:
<a href="{% url 'app01:reg' %}"></a>
Backend:
reverse('x:reg')
Configuration:
urlpatterns = [
url(r'^app01/', include('app01.urls', namespace='x')),
url(r'^app02/', include('app02.urls', namespace='y')),
]
Recommendation
Use app prefixes for clarity:
url('^reg/', views.reg, name='app01_reg')
Pseudo Static Pages
Convert dynamic pages to static-like appearance for SEO optimization.
Virtual Environments
Why Use Them?
Isolate dependencies per project.
Creation
Create a new Python interpreter instance with clean packages.
Django Version Differences
Django 1.X vs 2.X
- Use
url()in 1.X;path()in 2.X path()does not support regexre_path()supports regex likeurl()path()offers built-in converters
File Upload Handling
Form Requirements
- Method must be POST
- Enctype must be
multipart/form-data - CSRF middleware must be disabled in settings
Template
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="my_file">
<input type="submit">
</form>
Backend Code
def upload_file(request):
if request.method == 'POST':
file_obj = request.FILES.get('my_file')
with open(file_obj.name, 'wb') as fw:
for line in file_obj:
fw.write(line)
return render(request, 'upload.html')