神剑山庄资源网 Design By www.hcban.com

第二次修改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", "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重建数据库的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

标签:
django,models,重建数据库

神剑山庄资源网 Design By www.hcban.com
神剑山庄资源网 免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
神剑山庄资源网 Design By www.hcban.com

评论“django修改models重建数据库的操作”

暂无django修改models重建数据库的操作的评论...