我正在为具有多个应用程序的大型 Django 应用程序编写测试。作为这个过程的一部分,我逐渐为 Django 项目中不同应用程序的所有模型创建工厂。
但是,我在 FactoryBoy 中遇到了一些令人困惑的行为
我们的应用程序使用Profiles链接到默认auth.models.User模型的OneToOneField
class Profile(models.Model):
user = models.OneToOneField(User)
birth_date = models.DateField(
verbose_name=_("Date of Birth"), null=True, blank=True)
( ... )
Run Code Online (Sandbox Code Playgroud)
我为两种模型创建了以下工厂:
@factory.django.mute_signals(post_save)
class ProfileFactory(factory.django.DjangoModelFactory):
class Meta:
model = profile_models.Profile
user = factory.SubFactory('yuza.factories.UserFactory')
birth_date = factory.Faker('date_of_birth')
street = factory.Faker('street_name')
house_number = factory.Faker('building_number')
city = factory.Faker('city')
country = factory.Faker('country')
avatar_file = factory.django.ImageField(color='blue')
tenant = factory.SubFactory(TenantFactory)
@factory.django.mute_signals(post_save)
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = auth_models.User
username = factory.Faker('user_name')
first_name = factory.Faker('first_name')
last_name = factory.Faker('last_name') …Run Code Online (Sandbox Code Playgroud) 我正在创建一个 python 应用程序,其中包含一个数据库,其中包含不同足球比赛的结果。
我希望模型根据和字段result的值设置其字段。home_scoreaway_score
我经常使用 Django - 但这次不是,因为它将是一个简单的终端应用程序。save如果我是,我会使用下面方法中的一些代码对该方法进行子类化result。
作为 SQLAlchemy 的新手,我认为@hybrid_property装饰器是我想要实现的目标的一个很好的代理。
但是,当我为此模型运行单元测试时,它在以下行中失败
elif self.home_score > self.away_score:
出现以下错误:
TypeError: Boolean value of this clause is not defined
我已经包含了下面的模型,有人知道我做错了什么吗?
class Match(Base):
__tablename__ = 'matches'
id = Column(Integer, primary_key=True)
date = Column(Date, nullable=False)
home_id = Column(Integer, ForeignKey('teams.id'))
home = relationship(
"Team", back_populates='home_matches', foreign_keys=[home_id]
)
away_id = Column(Integer, ForeignKey('teams.id'))
away = relationship(
"Team", back_populates='away_matches', foreign_keys=[away_id]
)
home_score = Column(Integer, nullable=False)
away_score = Column(Integer, nullable=False) …Run Code Online (Sandbox Code Playgroud) 我有一个按年份列出的国家/地区列表,就像这样
country year founding_year other_vars
Fake 1900 1950 data
Fake 1901 1950 data
Fake 1902 1950 data
(...)
USE 1900 1901 data
USE 1901 1901 data
USE 1901 1901 data
Run Code Online (Sandbox Code Playgroud)
该founding_year是位在第一混乱,但什么数据集是干什么的,是其跟踪的国家are countries in 2001,每年-收集有关他们的各种统计数据。
不,我想创建一个图表来显示随着时间的推移国家的创建/建立。我已经有了yearX 轴的founding_year变量,该变量提供了我需要的信息 - 但是我在groupby操作时遇到了问题number of new nations per founding year
我使用以下命令:
df.groupby(['founding_years', 'country']).size()
Run Code Online (Sandbox Code Playgroud)
我选择了founding_year和country变量以确保我有唯一的对(因为每个国家有多行)
但是,这给了我一个错误的结果。
founding_year country
1945 Austria 46
Poland 46
1946 Jordan 46
Lebanon 46
Philippines 46
Syria 16 …Run Code Online (Sandbox Code Playgroud) 我有以下问题:
我有一个调查,其中包含大量对 Likert 问题的答案,如下所示:
id | Q1 | Q2 | Q3
1 5 3 1
2 3 4 1
3 2 3 1
Run Code Online (Sandbox Code Playgroud)
问题是并非所有问题都是朝着“同一方向”提出的。因此,Q1 中的“5”答案将表示肯定的答案。但是第二季度的 5 将意味着一个强烈的否定答案。
我们目前正在手动重新编码所有问题(因此将所有 Q2 5 替换为 1 等),但我想知道是否有更快的方法来解决这个问题。
我想过将所有答案除以 5 然后减去 1,但这从来没有给我整数。数学在这里并不是我的强项,所以我想知道这里是否有人可以帮助我
我希望通过比较A和B列表来打印缺少的值.
例如,当我print(a)告诉我[1,2,5,7,8,9,11,12]缺少和不同于A.
A = ['0', '0', '3', '4', '6', '6', '6', '6', '6', '6', '10', '10', '10']
B = ['1', '10', '2', '5', '0', '3', '4', '7', '8', '9', '6', '11', '12']
Run Code Online (Sandbox Code Playgroud)
我尝试了这个,但它不会工作.
a = []
for x in A:
for y in B:
if y != u:
a.append(y)
Run Code Online (Sandbox Code Playgroud)
有一个简单的方法吗?我一直在努力学习更多.希望有人可以提供帮助.
我正在开发一个webapp,用户可以在其中查看项目列表,并可以将某些项目标记为收藏夹.收藏夹以ID的数组形式提供,带有道具(this.props.favourites).为了防止重复的条目,如果item.id已经在this.props.favourites数组中,我想用"从收藏夹中删除"按钮替换"添加到收藏夹"按钮.
但是,三元If声明我在语法错误上崩溃了.然而,我认为我非常接近官方的例子(https://reactjs.org/docs/conditional-rendering.html).
这是我使用的代码:
render() {
const items = this.state.items.map((item, index) => (
<p key={index}>
{item.name}
</p>
{(this.props.favourites.include(item) ? (
<button>add fvourites</button>
) : (
<button>delete</button>
)}
));
return (
<div>
<button onClick={this.LoadApi}>Show fetch Items</button>
<div>{items}</div>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
有谁知道我做错了什么?
我有一个页面,用户可以在其中将 PDF/图像文件上传到他们的个人资料。这些文件的模型相对简单:
class ResumeItemFile(models.Model):
item = models.ForeignKey(ResumeItem, related_name='attachment_files')
file = models.FileField(
max_length=255, upload_to=RandomizedFilePath('resume_attachments'),
verbose_name=_('Attachment'))
name = models.CharField(max_length=255, verbose_name=_('Naam'), blank=True)
Run Code Online (Sandbox Code Playgroud)
我正在创建一个视图,其中链接到配置文件 ( item) 的所有文件都收集在一个 .zip 文件中。我在本地工作,但在生产中我运行在以下错误中NotImplementedError: This backend doesn't support absolute paths.
主要区别在于,在生产过程中,媒体文件是通过 S3 提供的
MEDIA_URL = 'https://******.s3.amazonaws.com/'
STATIC_URL = MEDIA_URL
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
Run Code Online (Sandbox Code Playgroud)
在我看来,我在attachments变量中创建了一个 ResumeItemFile 列表,它是一个如下所示的 dict列表:{'filename', ResumeItemFileObject}
for file in attachments:
storage = DefaultStorage()
filename = file[1]
file_extension = str(file[0].file).split('.')[-1]
file_object = storage.open(file[0].file.path, mode='rb')
filename, file_object.read())
file_object.close()
Run Code Online (Sandbox Code Playgroud)
虽然这在本地工作正常,但在暂存时它会在线上崩溃file_object = storage.open(file[0].file.path, …
我正在为 django 应用程序构建一些测试,并且正在使用 FactoryBoy
\n\n该Profile模型有一个gender字段,定义如下:
class Profile(models.Model):\n\n GENDER_CHOICES = (\n (u\'m\', _(u\'Male\')),\n (u\'f\', _(u\'Female\')),\n ) \n\n gender = models.CharField(\n max_length=2, choices=GENDER_CHOICES, verbose_name=_("Gender"),\n null=True, blank=True\n ) \nRun Code Online (Sandbox Code Playgroud)\n\n我想使用以下代码行随机化工厂男孩中该字段的值:
\n\nclass ProfileFactory(factory.Factory):\n (...)\n gender = factory.LazyFunction(random.choice([\'f\', \'m\']))\nRun Code Online (Sandbox Code Playgroud)\n\n但是,这会引发TypeError: \'str\' object is not callable错误\n使用旧的博客文章,我尝试了以下解决方案,该解决方案有效:
gender = factory.LazyAttribute(lambda x: random.choice([\'f\', \'m\']))
这解决了问题,但我不清楚为什么会这样。
\n\n的文档指出factory.LazyFunction:
The LazyFunction is the simplest case where the value of an attribute\n does not …Run Code Online (Sandbox Code Playgroud) 通过Thaian,已通过在“ test_create”函数的开头添加登录名解决了该问题,因为您需要登录该网站才能使用createview
我目前正在为createview编写测试,但无法向其中发布数据。
被测试的对象具有以下模型
class Role(models.Model):
name = models.CharField(max_length=255)
linked_tenant = models.ForeignKey(Tenant, blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)
并在以下(通用)视图中使用
class RolCreate(TenantRootedMixin, CreateView):
model = RolTemplate
form_class = RoleForm
def get_form_kwargs(self):
kwargs = super(RolCreate, self).get_form_kwargs()
kwargs['linked_tenant'] = self.request.tenant
return kwargs
def form_valid(self, form):
form.instance.linked_tenant = self.kwargs.get('tenant')
return super(RolCreate, self).form_valid(form)
def get_success_url(self, **kwargs):
return reverse('rol_list', args=[self.request.tenant.slug])
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的测试。
class RolCreate_tests(TestCase):
def setUp(self):
self.tenant = get_tenant()
self.role = get_role(self.tenant)
self.client = Client(HTTP_HOST='tc.tc:8000')
self.user = get_user(self.tenant)
def test_create(self):
response = self.client.post(reverse('rolcreate'), {'name' : 'new_object'})
self.assertEqual(response.status_code, 302)
test_against = Role.objects.get(name='new_object') …Run Code Online (Sandbox Code Playgroud) python ×6
django ×4
factory-boy ×2
pandas ×2
dataframe ×1
javascript ×1
jsx ×1
list ×1
post ×1
reactjs ×1
sqlalchemy ×1