Django Faker 递归外键

问题描述

我正在尝试使用 Faker 创建播种脚本。在我的 models.ContentCategory 中,parent_category一个递归外键。但是,我找不到将其翻译成我的伪造脚本的方法。我真的很乐意接受各种帮助!

这是我的models.py:

class ContentCategory(models.Model):
    name = models.CharField(blank=False,null=False,max_length=100)
    description = models.CharField(blank=False,max_length=100)
    parent_category = models.ForeignKey(
        "self",on_delete=models.DO_nothing,null=True,blank=True,parent_link=True,)
    # down here should be fixed after creating the sections model
    parent_section = models.ForeignKey(
        Sections,on_delete=models.CASCADE,null=True
    )

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "content category"
        verbose_name_plural = "Content Categories"

这是处理程序片段:

#seeding Content Category
        for _ in range(4):
            name = fake.word(ext_word_list=None)
            description = fake.sentence(nb_words=15,variable_nb_words=True,ext_word_list=None)
            #creating ids and parent ids
            cid = random.randint(1,4)
            # creating key for Sections
            ptid = random.randint(1,14)
            ContentCategory.objects.create(
                name=name,description=description,parent_category=cid,parent_section=ptid
            )
            check_content_categories = ContentCategory.objects.count().all() 

这里是完整的错误日志:

 python manage.py seed
Traceback (most recent call last):
  File "manage.py",line 21,in <module>
    main()
  File "manage.py",line 17,in main
    execute_from_command_line(sys.argv)
  File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/__init__.py",line 381,in execute_from_command_line
    utility.execute()
  File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/__init__.py",line 375,in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/base.py",line 323,in run_from_argv
    self.execute(*args,**cmd_options)
  File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/base.py",line 364,in execute
    output = self.handle(*args,**options)
  File "/home/myyagis/meethaq/be/be/api/management/commands/seed.py",line 104,in handle
    ContentCategory.objects.create(
  File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/manager.py",line 82,in manager_method
    return getattr(self.get_queryset(),name)(*args,**kwargs)
  File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/query.py",line 420,in create
    obj = self.model(**kwargs)
  File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/base.py",line 483,in __init__
    _setattr(self,field.name,rel_obj)
  File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py",line 206,in __set__
    raise ValueError(
ValueError: Cannot assign "1": "ContentCategory.parent_category" must be a "ContentCategory" instance. 

先谢谢你!

解决方法

已解决:

在模型中,外键表已经接受 blank=True,null=True,因此,我从播种脚本中丢弃了这些,它会自动用空值填充数据库。

非空字段的更好解决方案:

Model.objects.order_by('?').first() 确认使用。

递归外键接受模型自己的名称作为模型名称。

模型 UserCategory 的示例:

for _ in range(200):
            category = UserCategory.objects.order_by('?').first()
            email = fake.unique.ascii_free_email()
            password = fake.unique.word(ext_word_list=None)
            gender =fake.api_gender()
            first_name = fake.unique.first_name()
            last_name = fake.unique.last_name()
            phone_number = fake.country_calling_code() + fake.phone_number()
            birthday = fake.unique.date_of_birth()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...