如何在Django中进行自定义管理并使用CSV填充数据库?

huangapple go评论70阅读模式
英文:

how custom management work in django and can fill database with csv?

问题

我正在学习Django,使用的是《Django Web开发》这本书。

在这本书的第二章中,作者使用CSV文件填充数据库。有人可以解释一下这个文件以及Django自定义命令的工作原理吗?

Python 代码地址:
https://github.com/PacktPublishing/Web-Development-with-Django/blob/master/Chapter02/final/bookr/reviews/management/commands/loadcsv.py

CSV 文件地址:
https://github.com/PacktPublishing/Web-Development-with-Django/blob/master/Chapter02/final/bookr/reviews/management/commands/WebDevWithDjangoData.csv

我只知道它是如何工作的。

英文:

I am learning Django with the book web development with django
In the second chapter of the book, the author fills the database with a csv file.
Can anyone explain this file and how the django custom command works?

python code address:
https://github.com/PacktPublishing/Web-Development-with-Django/blob/master/Chapter02/final/bookr/reviews/management/commands/loadcsv.py

csv address:
https://github.com/PacktPublishing/Web-Development-with-Django/blob/master/Chapter02/final/bookr/reviews/management/commands/WebDevWithDjangoData.csv

i just know how it work

答案1

得分: 1

所有详细信息都在Django文档中:https://docs.djangoproject.com/en/4.1/howto/custom-management-commands/
但简而言之,django.core.management.base.BaseCommand有两个主要方法:

  • add_arguments:您将使用它来添加自定义命令的可选参数:python manage.py custom_command --argument1 --argument2
  • handle:在这个方法中,您将捕获命令的参数(位于options变量(字典)中)。因此,在您的字典中,您将有argument1argument2,可能会有一个值(取决于您的参数设置)
英文:

All details are in Django documentation: https://docs.djangoproject.com/en/4.1/howto/custom-management-commands/

But to put it in a nutshell, there are 2 major methods of a django.core.management.base.BaseCommand:

  • add_arguments: you will use it to add optional argument(s) to your custom command: python manage.py custom_command --argument1 --argument2
  • handle: In this method, you'll catch arguments of your commands (which are in the options var (dict). So in your dictionary, you'll have argument1 and argument2 with eventually a value (depending of your argument setup)

huangapple
  • 本文由 发表于 2023年4月11日 03:10:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979982.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定