django.db.utils.IntegrityError:表'Event_event'中具有主键'1'的行具有无效的外键:

我的活动模型

class Event(models.Model):
    name = models.CharField(max_length=100)
    start_date = models.DateField()
    end_date = models.DateField()
    TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones))
    timezone = models.CharField(max_length=32, choices=TIMEZONES)
    session=models.ForeignKey(Session,on_delete=models.CASCADE)
    slug = models.SlugField(unique=True, editable=False, max_length=100)

和我的会话模型

class Session(models.Model):
    name=models.CharField(max_length=100)
    start_date=models.DateField()
    end_date=models.DateField()
    speaker=models.CharField(max_length=100)
    slug = models.SlugField(unique=True, editable=False, max_length=100)

创建测试时出现错误。 我应该在会话部分做什么? 这是我的测试代码

class CreateTest(APITestCase):
    def test_create_event(self):
        url = 'http://127.0.0.1:8000/api/event/create'
        data = Event.objects.create(
            name="deneme 5",
            start_date="2020-05-23",
            end_date="2020-05-26",
            timezone="Etc/GMT",
            session_id='1'
            )
        response = self.client.post(url,data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
评论
  • 带我飞
    带我飞 回复

    You get this error because, you haven't any Session record which has id 1. You must create Session object before create Event object and provide this created session id to event object. In Django APITestCase, new empty database is created for all test functions all time.