我尝试使用django创建一个简单的rest api,但是当我迁移我的模型时,我收到此错误:
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1789, in get_prep_value
return float(value)
ValueError: could not convert string to float:
笑话是:我的模型中没有FloatField()类型的字段!!
问题可能来自srializer.py但是......
my_api / model.py:
class Bucketlist(models.Model):
"""This class represents the bucketlist model."""
name = models.CharField(max_length=255, blank=False, unique=True,default="")
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
def __str__(self):
"""Return a human readable representation of the model instance."""
return "{}".format(self.name)
class Meta:
"""test for admin interface"""
verbose_name_plural = "Ma list de courses"
my_api / Serializer.py:
class BucketlistSerializer(serializers.ModelSerializer):
"""Serializer to map the Model instance into JSON format."""
class Meta:
"""Meta class to map serializer's fields with the model fields."""
model = Bucketlist
fields = '__all__' # == fields = ('id', 'name', 'date_created', 'date_modified')
read_only_fields = ('date_created', 'date_modified')
my_api / View.py:
class CreateView(generics.ListCreateAPIView):
"""This class defines the create behavior of our rest api."""
queryset = Bucketlist.objects.all()
serializer_class = BucketlistSerializer
def perform_create(self, serializer):
"""Save the post data when creating a new bucketlist."""
serializer.save()
my_api / Test.py:
class ViewTestCase(TestCase):
"""Test suite for the api views."""
def setUp(self):
"""Define the test client and other test variables."""
self.client = APIClient()
self.bucketlist_data = {'name': 'Go to Ibiza'}
self.response = self.client.post(
reverse('create'),
self.bucketlist_data,
format="json")
def test_api_can_create_a_bucketlist(self):
"""Test the api has bucket creation capability."""
self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)
my_api / url.py:
urlpatterns = [
url(r'^bucketlists/$',views.CreateView.as_view(), name="create"),
url(r'^$', views.BucketlistView.as_view(), name ="list")
] urlpatterns = format_suffix_patterns(urlpatterns)