python – Django rest-framework
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – Django rest-framework,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含8203字,纯文字阅读大概需要12分钟。
内容图文
![python – Django rest-framework](/upload/InfoBanner/zyjiaocheng/744/b9663f4f9e0b4ead9a60333993cdd1eb.jpg)
我正在编写一个基于Django rest-framework的rest API应用程序.我想以JSON格式返回我的模型数据
我的模特是:
from os import path
from django.db import models
from django.contrib import admin
from django.core.files.storage import FileSystemStorage
#------------------------------------------------------------------------------
projectDirPath = path.dirname(path.dirname(__file__))
storeImageDir = FileSystemStorage(location=projectDirPath + '/couponRestApiApp/stores')
class tags(models.Model):
""" This is the tag model """
tag = models.CharField(max_length=15) # Tag name
tagDescription = models.TextField() # Tag Description
tagSlug = models.CharField(max_length=400) # Extra info can be added to the existing tag using this field
createdAt = models.DateTimeField(auto_now_add=True) # Time at which tag is created
updatedAt = models.DateTimeField(auto_now=True) # Time at which tag is updated
def __unicode__(self):
"""Method to display string correctly"""
return unicode(self.tag)
class Meta:
"""Meta class to control display Behavior of the Model name """
verbose_name_plural = "Tags"
class stores(models.Model):
""" This is the store model """
storeName = models.CharField(max_length=15) # Store Name
storeDescription = models.TextField() # Store Description
storeURL = models.URLField() # Store URL
storePopularityNumber = models.IntegerField(max_length=1) # Store Popularity Number
storeImage = models.ImageField(upload_to="images") # Store Image
storeSlug = models.CharField(max_length=400) # This is the text you see in the URL
createdAt = models.DateTimeField(auto_now_add=True) # Time at which store is created
updatedAt = models.DateTimeField(auto_now=True) # Time at which store is updated
storeTags = models.ManyToManyField(tags) # All the tags associated with the store
def __unicode__(self):
"""Method to display string correctly"""
return unicode(self.storeName)
def StoreTags(self):
return '\n'.join([s.tag for s in self.storeTags.all()])
def StoreImage(self):
return '<img src="/media/couponRestApiApp/stores/%s" height="150"/>' % (self.storeImage)
StoreImage.allow_tags = True
class Meta:
"""Meta class to control display Behavior of the Model name """
verbose_name_plural = "Stores"
class coupons(models.Model):
""" This is the coupon model """
couponValue = models.CharField(max_length=4) # Coupon value in RS.
couponDescription = models.TextField() # Coupon Description
couponURL = models.URLField() # Coupon click URL
couponStore = models.ForeignKey(stores) # Key of coupon to store
tagName = models.ForeignKey(tags,on_delete=models.PROTECT) # Tag names associated to coupon
success = models.TextField() # Count of the number of times people have made it work
failures = models.TextField() # Count of the number of times this has failed
lastTested = models.DateTimeField(auto_now=True) # When was the coupon last tested
createdAt = models.DateTimeField(auto_now_add=True)
updatedAt = models.DateTimeField(auto_now=True)
class Meta:
"""Meta class to control display Behavior of the Model name """
verbose_name_plural = "Coupons"
class app(models.Model):
""" This is the application model which is using the API """
appName = models.CharField(max_length=20) # Application name
appDomain = models.CharField(max_length=20) # Application description
appKey = models.TextField() # Application Key
createdAt = models.DateTimeField(auto_now_add=True) # Time at which Application is added is created
updatedAt = models.DateTimeField(auto_now=True) # Time at which Application details are updated
class Meta:
"""Meta class to control display Behavior of the Model name """
verbose_name_plural = "Apps"
class subscriptions(models.Model):
""" These are the emails that are subscribing """
app = models.CharField(max_length=20) # The application where the email came from
store = models.CharField(max_length=20) # The optional store on which the email wants an update
tag = models.CharField(max_length=20) # The optional tag on which the email wants an update
emailID = models.EmailField() # EmailID of the registered user
active = models.BooleanField(default=True) # They may have unsubscribed
createdAt = models.DateTimeField(auto_now_add=True) # Time at user subscribed to the alerts
updatedAt = models.DateTimeField(auto_now=True) # Time at which user updated its subscription
class Meta:
"""Meta class to control display Behavior of the Model name """
verbose_name_plural = "Subscriptions"
class tagsAdmin(admin.ModelAdmin):
list_display = ('tag', 'tagDescription', 'tagSlug')
class storesAdmin(admin.ModelAdmin):
list_display = ('storeName','storeDescription','storeURL',
'storePopularityNumber','StoreImage',
'storeSlug','createdAt','createdAt','StoreTags'
)
class couponsAdmin(admin.ModelAdmin):
list_display = ('couponValue','couponDescription','couponValue',
'couponURL', 'couponStore','tagName','success',
'failures','createdAt','updatedAt'
)
class appsAdmin(admin.ModelAdmin):
list_display = ('appName','appDomain','appKey',
'createdAt','updatedAt'
)
class subcriptionsAdmin(admin.ModelAdmin):
list_display = ('app','store','tag','emailID',
'active','createdAt','updatedAt'
)
admin.site.register(tags,tagsAdmin)
admin.site.register(stores,storesAdmin)
admin.site.register(coupons,couponsAdmin)
admin.site.register(app,appsAdmin)
admin.site.register(subscriptions,subcriptionsAdmin)
#------------------------------------------------------------------------------
我在views.py中写了一个类:
from rest_framework import status
from rest_framework.views import View
from rest_framework.response import Response
from couponRestApiApp.models import app,coupons,stores,subscriptions,tags
————————————————– —————————-
class getAllStores(View):
"""
Provides access to all orders within the system.
"""
def get(self, request):
"""
Return a list of all orders.
"""
storeResponse = [i.storeName for i in stores.objects.all()]
print storeResponse
return (storeResponse)
我的URL.py是:
from django.contrib import admin
from couponRestApiApp.views import getAllStores
from django.conf.urls import patterns, include, url
#------------------------------------------------------------------------------
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': "/home/vaibhav/TRAC/coupon-rest-api/couponRestApi/", 'show_indexes': False}),
url(r'^stores/$',getAllStores.as_view(), name='getAllStores'),
)
但是如果我发出请求(http:// localhost:8000 / stores /),则抛出以下错误:’list’对象没有属性’status_code’
请告诉我如何使用rest-framework将模型数据序列化为JSON对象….
解决方法:
class getAllStores(generics.ListAPIView,APIView):
"""
Provides access to all orders within the system.
"""
model = stores # Model name
serializer_class = getAllStoresDetailSerializer # Call serializer
def get_queryset(self):
return stores.objects.filter()
串行:
class getAllStoresDetailSerializer(serializers.ModelSerializer):
storeTags = serializers.Field(source='StoreTags')
storeImage = serializers.Field(source='storeImage')
class Meta:
model = stores
fields = ('storeName','storeDescription',
'storeURL','storePopularityNumber','storeImage','storeTags',
'storeSlug','createdAt','updatedAt','StoreCoupons'
)
我认为你必须修改storeImage方法,以便在服务器上提供图像的路径……或者为此定义新的方法….
内容总结
以上是互联网集市为您收集整理的python – Django rest-framework全部内容,希望文章能够帮你解决python – Django rest-framework所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。