您好,登錄后才能下訂單哦!
第二次修改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 >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", "stanzas": 1}, .... ], }
效果就是能在一個json頁面下序列化出多個不同的model數據
我們還可以對每個表的數據進行分頁
from drf_multiple_model.pagination import MultipleModelLimitOffsetPagination
views下可以這么寫
class LimitPagination(MultipleModelLimitOffsetPagination):
default_limit = 10
意思是每個model默認顯示前十條數據
如果前端需要,url上可以加上limit=5,自定義默認顯示前五條數據
更多詳細內容,github搜索DjangoRestMultipleModels
以上這篇django修改models重建數據庫的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。