我为api和模型创建测试。问题是测试是否创建了模型。 用户模型就是这个:
class User(AbstractUser):
CUSTOMER = 1
EXECUTER = 2
USER_TYPES = (
(CUSTOMER, 'Customer'),
(EXECUTER, 'Executer'),
)
user_type = models.IntegerField(choices=USER_TYPES, default=EXECUTER, verbose_name='Тип пользователя')
balance = models.DecimalField(decimal_places=2, max_digits=7, default=0, verbose_name='Баланс')
def __str__(self):
return self.username
任务模型如下:
class Task(models.Model):
title = models.CharField(max_length=255, verbose_name='Заголовок')
description = models.CharField(max_length=255, verbose_name='Описание')
money = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='Цена')
assignee = models.ForeignKey('users.User', related_name='assignee', null=True, verbose_name='Исполнитель')
created_by = models.ForeignKey('users.User', related_name='created_by', verbose_name='Кем был создан')
我想测试模型创建,但测试模型并不想制作。问题在受让人中并由字段创建。 这是我的考验:
def test_creating_models_instance(self):
User.objects.create(username="assignee", first_name="First_name_2", last_name="Surname_2",
user_type=2, balance="16155.00")
User.objects.create(username="created_by", first_name="First_name_1", last_name="Surname_1",
user_type=1, balance="16155.00")
Task.objects.create(title="Task_1", description="Description_1", money="155.00",
assignee="assignee", created_by="created_by")
我错了:
self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "'assignee'": "Task.assignee" must be a "User" instance.
答案 0 :(得分:1)
您需要使用实例而不是字符串:
def test_creating_models_instance(self):
assignee = User.objects.create(
username="assignee", first_name="First_name_2",
last_name="Surname_2", user_type=2, balance="16155.00")
created_by = User.objects.create(
username="created_by", first_name="First_name_1",
last_name="Surname_1", user_type=1, balance="16155.00")
Task.objects.create(title="Task_1", description="Description_1", money="155.00",
assignee=assignee, created_by=created_by)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^