如何为Django choices参数导入数据?

时间:2019-05-05 19:54:19

标签: python django django-models

我正在创建一个具有字符字段的模型,称为“国家”。

我刮了一下网络,并创建了一个元组(在另一个python文件中),其中包含我希望用户可以选择的国家/地区。另一个文件中的元组完全符合Django要求的格式,例如((“ BR”,“ Brazil”),(“ US”,“ The United States”))。

现在,如何在“ choices”参数(例如myfile.COUNTRIES)中导入该国家/地区元组?

我根本不知道该怎么做。如何在Django项目中导入这些数据?有生产的最佳实践或建议吗?

class Profile(models.Model):

    COUNTRIES = ???

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default="default.jpg", upload_to="profile_pics")
    countries = models.CharField(max_length=100, choices=COUNTRIES, blank=False, null=True)

这是包含元组的文件:

from bs4 import BeautifulSoup
from urllib.request import urlopen

# Accessing website.
url = "..."
http_response = urlopen(url)
html = BeautifulSoup(http_response, "html.parser")

# Getting to the table.
table = html.find("table", {"class":"table table-hover"})

# Getting the table rows.
table_rows = table.find("tbody").find_all("tr")

# Getting the country names.
countries = ()
for row in table_rows:
    td = row.find_all("td")[1]
    name = td.find("a").get_text()
    universities += (name, name)

1 个答案:

答案 0 :(得分:0)

更新的答案

在抓取数据时,需要将其存储在模型中使用的某个位置。我建议使用数据库。您可以创建一个名为Country的模型:

class Country(models.Model):
    code = models.CharField(max_length=10)
    name = models.CharField(max_length=20)

并像下面这样在脚本中使用它:

for row in table_rows:
    td = row.find_all("td")[1]
    name = td.find("a").get_text()
    Country.objects.get_or_create(name=name, code=name)

要在脚本中使用模型,可以将脚本转换为custom django management command

# your_app/management/commands/generate_countries.py
from django.core.management.base import BaseCommand
from django.utils import timezone
from bs4 import BeautifulSoup
from urllib.request import urlopen


class Command(BaseCommand):
    help = 'Generate Countries'

    def handle(self, *args, **kwargs):
        url = "..."
        http_response = urlopen(url)
        html = BeautifulSoup(http_response, "html.parser")
        table = html.find("table", {"class":"table table-hover"})
        table_rows = table.find("tbody").find_all("tr")


        for row in table_rows:
            td = row.find_all("td")[1]
            name = td.find("a").get_text()
            Country.objects.get_or_create(name=name, code=name)

,以便您可以像这样使用它:python manage.py generate_countries

在这样的其他模型中使用国家/地区:

class Profile(models.Model):
   ...
   countries = models.ForeignKey(Country, on_delete=models.DO_NOTHING)

旧答案

假设您的文件名为countries.py,在该文件中,元组如下所示:

COUNTRIES = (
    ("BR", "Brazil"),
    ("US", "The United States")
    ...
)

现在,假设它与models.py在同一文件夹中,那么您可以像这样简单地导入它:

from .countries import COUNTRIES
# if countries.py is in x module(folder with __init__.py file) then use
# from x.countires import COUNTRIES

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default="default.jpg", upload_to="profile_pics")
    countries = models.CharField(max_length=100, choices=COUNTRIES, blank=False, null=True)