gpt4 book ai didi

python - 生成假数据以填充数据库

转载 作者:行者123 更新时间:2023-12-02 19:21:07 25 4
gpt4 key购买 nike

我正在尝试使用 factory boy 和 faker 为我正在构建的网站生成一些虚假数据。这是我的 models.py:

# External Imports
from django.db import models
import uuid

# Internal Imports
from applications.models.application import Application
from users.models.user import User
from .session import Session

# Fake data
import factory
import factory.django
import factory.fuzzy
from datetime import datetime
from faker import Faker
from faker.providers import BaseProvider
import random


class ButtonClick(models.Model):
"""**Database model that tracks and saves button clicks for an application**
"""
# identifier
id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)

# info
button_name = models.CharField(max_length=128, null=True, blank=True)
application = models.ForeignKey(
Application, related_name='button_clicks', null=True, blank=True, on_delete=models.CASCADE)
user = models.ForeignKey(
User, related_name='button_clicks', null=True, blank=True, on_delete=models.CASCADE)
session = models.ForeignKey(
Session, related_name='button_clicks', null=True, blank=True, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now=True)

class Meta:
db_table = 'button_clicks'
ordering = ('-timestamp', )

def __str__(self):
return f'{self.application} - {self.button_name}'

fake = Faker()
faker = Factory.create()


class ApplicationFactory(factory.DjangoModelFactory):
class Meta:
model = Application

application = factory.LazyAttribute(lambda _: faker.word())


class FakeButtonClick(factory.django.DjangoModelFactory):
class Meta:
model = ButtonClick

button_name = factory.Faker('first_name')
application = factory.SubFactory(ApplicationFactory)
user = factory.Faker('name')
session = factory.Faker('random_int')
timestamp = factory.Faker('date')

当我尝试在终端中运行以下代码时,出现错误:

>>> from analytics.models.button_click import FakeButtonClick
>>> for _ in range(200): FakeButtonClick.create()
...

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/factory/base.py", line 564, in create
return cls._generate(enums.CREATE_STRATEGY, kwargs)
File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/factory/django.py", line 141, in _generate
return super(DjangoModelFactory, cls)._generate(strategy, params)
File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/factory/base.py", line 501, in _generate
return step.build()
File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/factory/builder.py", line 279, in build
kwargs=kwargs,
File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/factory/base.py", line 315, in instantiate
return self.factory._create(model, *args, **kwargs)
File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/factory/django.py", line 185, in _create
return manager.create(*args, **kwargs)
File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/django/db/models/query.py", line 431, in create
obj = self.model(**kwargs)
File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/django/db/models/base.py", line 482, in __init__
_setattr(self, field.name, rel_obj)
File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 219, in __set__
self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "9714": "ButtonClick.application" must be a "Application" instance.

我过去使用 factory boy 和 faker 创建了一些非常简单的数据,但回溯似乎暗示我需要在我的 FakeButtonClick 类中创建一个应用程序实例?我检查了文档,应用程序似乎不是工厂男孩/伪造者的可用实例。我需要自己创建实例吗?也许是一个子工厂?

最佳答案

您的 ButtonClick 模型有 3 个字段定义为 ForeignKey:applicationusersession

当您想要创建一个 ButtonClick 实例时,Django 要求您为定义为 ForeignKey 的每个字段提供一个有效值 — 在这里,这意味着提供模型实例或 None(因为那些 ForeignKey 可以为 null)。

对于 FactoryBoy,这意味着您必须:

  1. 为每个模型定义一个 Factory 类。
  2. 使用指向每个字段的工厂的 factory.SubFactory

一个例子是:


class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
username = factory.Faker('username')

class SessionFactory(factory.django.DjangoModelFactory):
class Meta:
model = Session
uuid = factory.Faker('uuid4')
user = factory.SubFactory(UserFactory)

class ApplicationFactory(factory.django.DjangoModelFactory):
class Meta:
model = Application
name = factory.Faker('name')

class ButtonClickFactory(factory.django.DjangoModelFactory):
class Meta:
model = ButtonClick
user = factory.SubFactory(UserFactory)
# Ensure that click.user == click.session.user
session = factory.SubFactory(SessionFactory, user=factory.SelfAttribute('..user'))
application = factory.SubFactory(ApplicationFactory)

可以看看at the docs .

顺便说一下,FactoryBoy 的 faker integration ,不需要直接导入:factory.Faker('uuid4')等同于faker.Faker().uuid4()

关于python - 生成假数据以填充数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63044893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com