在网上看到都是使用Django的models和makemigration,migrate命令来创建新表,并使用。可是我的数据已经存在了已经创建好,并且已经存储有数据了,不能再重新创建新表了。了解Django的表明和models名称的映射关系就可以让Django使用已经存在的表。
假如在Django存在models如下:
[python] view plain copy
from django.db import models
# Create your models here.
class Sciencenews(models.Model):
id = models.CharField(max_length=36,primary_key=True)
first_module = models.CharField(max_length=30,default="News")
second_module = models.CharField(max_length=30,default="Latest News")
title = models.CharField(max_length=300)
author = models.CharField(max_length=60,null=True)
publish_date = models.CharField(max_length=35,null=True)
content = models.TextField(null=True)
crawl_date = models.CharField(max_length=35,null=True)
from_url = models.CharField(max_length=350,null=True)
执行数据迁移命令:[python] view plain copy
python manage.py makemigration
python manage.py migrate
会在数据库中生成名称为show_sciencenews的数据表。show为应用名称,此处我的应用名称为show。可以看到Django创建表的命名规则:应用名_模型名。我的存储爬取到的数据的表格名称原来为science_news,想要Django使用它,而不是创建新的表,只需要把的它的名称改为:应用名_要与该表映射的models名称,在此处我改为show_sciencenews。然后使用如上的数据迁移命令,这时可能会提示数据表已经存在的错误,不用理会,models已经和数据表映射上了。接下来只需要正常使用models和数据表就可以了。
django创建数据库表方法如下:
catcher:mysite catcher$ python manage.py makemigrations booksMigrations for 'books':
0001_initial.py:
- Create model Author
- Create model Book
- Create model Publisher
- Add field publisher to book
catcher:mysite catcher$ python manage.py sqlmigrate books 0001
BEGIN
--
-- Create model Author
--
CREATE TABLE "books_author" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "first_name" varchar(30) NOT NULL, "last_name" varchar(40) NOT NULL, "email" varchar(254) NOT NULL)
--
-- Create model Book
--
CREATE TABLE "books_book" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(100) NOT NULL, "publication_date" date NOT NULL)
CREATE TABLE "books_book_authors" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "book_id" integer NOT NULL REFERENCES "books_book" ("id"), "author_id" integer NOT NULL REFERENCES "books_author" ("id"))
--
-- Create model Publisher
--
CREATE TABLE "books_publisher" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(30) NOT NULL, "address" varchar(50) NOT NULL, "city" varchar(60) NOT NULL, "state_province" varchar(30) NOT NULL, "country" varchar(50) NOT NULL, "website" varchar(200) NOT NULL)
--
-- Add field publisher to book
--
ALTER TABLE "books_book" RENAME TO "books_book__old"
CREATE TABLE "books_book" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(100) NOT NULL, "publication_date" date NOT NULL, "publisher_id" integer NOT NULL REFERENCES "books_publisher" ("id"))
INSERT INTO "books_book" ("publication_date", "publisher_id", "id", "title") SELECT "publication_date", NULL, "id", "title" FROM "books_book__old"
DROP TABLE "books_book__old"
CREATE INDEX "books_book_2604cbea" ON "books_book" ("publisher_id")
COMMIT
catcher:mysite catcher$
catcher:mysite catcher$ sudo python manage.py migratePassword:Operations to perform: Apply all migrations: admin, contenttypes, books, auth, sessionsRunning migrations: Rendering model states... DONE Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying books.0001_initial... OK Applying sessions.0001_initial... OKcatcher:mysite catcher$
如果你使用 Django 的模型表单 (model form) 生成表单,可以使用 Django 查询数据库进行筛选,以便仅显示与特定用户相关的分类。首先,在视图函数中,查询数据库并返回与特定用户相关的分类:
from django.shortcuts import render
from .models import Category
def my_view(request):
user_categories = Category.objects.filter(user=request.user)
return render(request, 'my_template.html', {'categories': user_categories})
然后,在模板中,您可以在生成表单时使用该分类集:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
最后,在表单类中,您可以重写初始化方法,以仅使用用户分类:
from django import forms
from .models import Table2
class Table2Form(forms.ModelForm):
class Meta:
model = Table2
fields = ('category',)
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['category'].queryset = Category.objects.filter(user=user)
最后,在视图函数中实例化表单,并将用户传递给表单类:
from django.shortcuts import render
from .forms import Table2Form
def my_view(request):
user_categories = Category.objects.filter(user=request.user)
form = Table2Form(request.user, instance=table2_instance)
return render(request, 'my_template.html', {'form': form})
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)