我正在使用M2M模型创建unittest。
models.py
from django.contrib.gis.db import models
from geoposition.fields import GeopositionField
from model_controller.models import AbstractModelController
from soken_web.apps.customers.models import Customer
class House(models.Model):
...
customers = models.ManyToManyField(Customer, related_name='houses') # Use M2M in case family member do same thing
第一个测试用例运行良好
但第二个不是。
tests.py
import copy
from django.contrib.auth.models import User
from model_mommy import mommy
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase, APIClient
from soken_web.apps.customers.models import Customer
from soken_web.apps.houses.models import House
class HouseTest(APITestCase):
def setUp(self):
self.client = APIClient()
self.soken_staff = mommy.make(User, username='spearhead')
self.customer = mommy.make(Customer)
self.data = {
'address_line_1': "testing data",
'address_line_2': "testing data",
'prefecture': "testing data",
'town': "testing data",
'city': "testing data",
'building': "testing data",
'postal_code': "10330",
'location': "13.747288, 100.528155",
'customers': self.customer.id,
}
def test_create_house(self):
self.client.force_authenticate(user=self.soken_staff)
res = self.client.post(reverse('api:house-list'), data=self.data)
self.assertEqual(201, res.status_code)
self.assertEqual(1, res.data.get('id')) # Confirm that mobile known ID
def test_update_house(self):
user = User.objects.create(username='aoc')
self.client.force_authenticate(user=user)
data = copy.deepcopy(self.data)
data['created_user'] = self.soken_staff
data['updated_user'] = self.soken_staff
house = House.objects.create(**data)
house.customers.add(self.customer)
house.refresh_from_db()
patch = {
"town": "MBK",
}
res = self.client.patch(reverse('api:house-detail', kwargs={'pk': house.id}), data=patch)
self.assertEqual(200, res.status_code)
背景
在test_update_house
。我必须创建样本,然后patch
。我不使用model_mommy
的原因是因为{class 1}}
GeopositionField
的类属性model_mommy
问题:
虽然我明确地.create()
然后refresh_from_db()
ORM提出错误。
ValueError: "<House: House object>" needs to have a value for field "id" before this many-to-many relationship can be used.