我正在创建一个具有POST
端点的Web应用程序,该应用程序执行以下两项操作:
POST
版的数据(大学评论)保存在数据库中。这是它的代码:
if request.method == 'POST':
review = Review(university=university,
user=User.objects.get(pk=1),
summary=request.POST['summary'])
review.save()
return HttpResponseRedirect(reverse('university_overview', args=(university_id,)))
我尚未实现将用户数据传递到端点的功能,这就是为什么要使用pk=1
将所有内容保存到用户下的原因。
我的测试如下:
class UniversityAddReviewTestCase(TestCase):
def setUp(self):
user = User.objects.create(username="username", password="password", email="email")
university = University.objects.create(name="Oxford University", country="UK", info="Meh", rating="9")
Review.objects.create(university=university, summary="Very nice", user_id=user.id)
Review.objects.create(university=university, summary="Very bad", user_id=user.id)
new_review = {
'summary': 'It was okay.'
}
self.response = Client().post('/%s/reviews/add' % university.id, new_review)
def test_database_updated(self):
self.assertEqual(len(Review.objects.all()), 3)
结果是这样的:
File ".../core/views.py", line 20, in detail
user=User.objects.get(pk=1),
File ".../ENV/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File ".../ENV/lib/python3.6/site-packages/django/db/models/query.py", line 403, in get
self.model._meta.object_name
django.contrib.auth.models.DoesNotExist: User matching query does not exist.
为什么会这样?我知道我正在创建的用户有一个pk=1
,就像我在测试过程中实际打印它的时候是1。
答案 0 :(得分:1)
pk
由数据库定义。在测试中可能使它不等于1。
在您的setUp方法中尝试
user = User.objects.create_user(
username="username",
password="password",
email="test@example.com",
id=1
)
assert user.pk == 1
答案 1 :(得分:0)
利用self
的优势,然后您可以尝试以下方法:
class UniversityAddReviewTestCase(TestCase):
def setUp(self):
self.user = User.objects.create(
username="username",
password="password",
email="email")
....
然后
if request.method == 'POST':
review = Review(
university=university,
user=self.user,
summary=request.POST['summary'])
review.save()