1. 程式人生 > 程式設計 >django修改models重建資料庫的操作

django修改models重建資料庫的操作

第二次修改models.py以後再次

python manage.py makemigrations

提示如下

You are trying to add a non-nullable field 'address' to xc_users without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows) 2) Qu

於是刪除資料庫表,繼續報相同的錯誤

makemigration需要指定名稱,然後migrate才能識別兩次<span style="font-family: Arial,Helvetica,sans-serif;">makemigrations的不同</span>

python manage.py makemigrations --name sqlname

然後再執行:

python manage.py migrate

成功解決問題!

補充知識:django rest framework如何一次性序列化同一個資料庫下多個model表資料在一個json頁面下

在django專案中,首先我們要安裝django-rest-mutiple-models

pip install django-rest-multiple-models

然後在setting配置中配置一下APP

INSTALLED_APPS = (
 ....
 'drf_multiple_model',)


在我們的views檢視函式下引入

from drf_multiple_model.views import ObjectMultipleModelAPIView

如下兩個模型

class Play(models.Model):
 genre = models.CharField(max_length=100)
 title = models.CharField(max_length=200)
 pages = models.IntegerField()
 
class Poem(models.Model):
 title = models.CharField(max_length=200)
 style = models.CharField(max_length=100)
 lines = models.IntegerField()
 stanzas = models.IntegerField()

序列化如下

class PlaySerializer(serializers.ModelSerializer):
 class Meta:
 model = Play
 fields = ('genre','title','pages')
 
class PoemSerializer(serializers.ModelSerializer):
 class Meta:
 model = Poem
 fields = ('title','stanzas')

views中我們可以這麼寫,繼承一個ObjectMutipleModelAPIView

from drf_multiple_model.views import ObjectMultipleModelAPIView
 
class TextAPIView(ObjectMultipleModelAPIView):
 querylist = [
 {'queryset': Play.objects.all(),'serializer_class': PlaySerializer},{'queryset': Poem.objects.filter(style='Sonnet'),'serializer_class': PoemSerializer},....
 ]

如果我們使用的url是router,那這裡我們就應該繼承ObjectMutipleModelAPIViewset

具體的引入

from drf_multiple_model.viewsets import ObjectMultipleModelAPIViewSet

DRF頁面的顯示效果如下

{
 "Play" : [
 {"genre": "Comedy","title": "A Midsummer Night"s Dream","pages": 350},{"genre": "Tragedy","title": "Romeo and Juliet","pages": 300},....
 ],"Poem" : [
 {"title": "Shall I compare thee to a summer"s day","stanzas": 1},{"title": "As a decrepit father takes delight",}

效果就是能在一個json頁面下序列化出多個不同的model資料

我們還可以對每個表的資料進行分頁

from drf_multiple_model.pagination import MultipleModelLimitOffsetPagination

views下可以這麼寫

class LimitPagination(MultipleModelLimitOffsetPagination):
default_limit = 10

意思是每個model預設顯示前十條資料

如果前端需要,url上可以加上limit=5,自定義預設顯示前五條資料

更多詳細內容,github搜尋DjangoRestMultipleModels

以上這篇django修改models重建資料庫的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。