当我尝试通过我的项目API使用foreignkey(在本例中为2)创建一个对象时,tastypie也尝试创建相关对象(此处为order&participant):
class ParticipationResource(ModelResource):
order = fields.ForeignKey(Order, 'order', full=True,)
participant = fields.ForeignKey(UserProfile, 'participant', full=True)
class Meta:
authorization = Authorization()
queryset = Participation.objects.all()
resource_name = 'participation'
fields = ['id', 'order', 'participant', 'products', 'created_at', 'modified_at']
filtering = {
'participant': ALL
}
detail_allowed_methods = ['get', 'post', 'put', 'delete',]
always_return_data = True
Run Code Online (Sandbox Code Playgroud)
发布的数据:
{
"order": {
"id":"1",
"resource_uri":"/api/v1/order/1/"
...
},
"participant":{
"id":"1",
"resource_uri":"/api/v1/participant/1/"
...
},
"products":[]
}
Run Code Online (Sandbox Code Playgroud)
错误消息(network_id是用户配置文件模型上的外键):
"error_message": "app_user_profile.network_id may not be NULL",
Run Code Online (Sandbox Code Playgroud)
你可以看到我在我的POST请求中发送完整的对象,我只尝试了resource_uri并且工作正常,问题是我需要客户端渲染的完整对象(我使用的是Backbone,模型是自动渲染).那我该怎么办?有没有办法让tastypie不创建相关对象?
当我尝试访问http:// localhost:8000/api/goal /?format = json时出现以下错误:
ImproperlyConfigured at /api/goal/
The included urlconf <property object at 0x262bb50> doesn't have any patterns in it
Run Code Online (Sandbox Code Playgroud)
这是我添加到我的urls.py中的内容:
goal_resource = GoalResource
...
url(r'^api/', include(goal_resource.urls)),
Run Code Online (Sandbox Code Playgroud)
这是我的api.py:
class GoalResource(ModelResource):
class Meta:
queryset = Goal.objects.all()
resource_name = 'goal'
Run Code Online (Sandbox Code Playgroud)
什么可能出错?
我需要在tastypie资源中执行过滤器查询.输入应该是url的标题,例如
new Ext.data.Store({
proxy: {
url :'api/users/'
type: "ajax",
headers: {
"Authorization": "1"
}
}
})
Run Code Online (Sandbox Code Playgroud)
我在下面试过
from tastypie.authorization import Authorization
from django.contrib.auth.models import User
from tastypie.authentication import BasicAuthentication
from tastypie import fields
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from tastypie.validation import Validation
from userInfo.models import ExProfile
class UserResource(ModelResource,request):
class Meta:
queryset = User.objects.filter(id=request.META.get('HTTP_AUTHORIZATION'))
resource_name = 'user'
excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser']
authorization = Authorization()
authentication=MyAuthentication()
Run Code Online (Sandbox Code Playgroud)
它在说name 'request' is not defined.如何在ORM上传递过滤器?
我扩展django User了我的自定义字段,现在我需要从自定义表返回一个json输出以及username表单父表.
我在查询集中尝试了select_related但它没有返回 username
楷模
class ExProfile(models.Model):
user = models.ForeignKey(User, unique=True)
cell_phone = models.CharField(max_length=200, blank=True)
api_key= models.CharField(max_length=200, blank=True)
termination_date=models.DateField()
picture=models.ImageField(upload_to='profile',blank=True)
email=models.EmailField()
homeAddress=models.CharField(max_length=200,blank=True)
homeNumber=models.CharField(max_length=200,blank=True)
Run Code Online (Sandbox Code Playgroud)
资源
class ProfileResource(ModelResource):
class Meta:
# the queryset below is working like ExProfile.objects.all() as it is not
# returning username in json
queryset =ExProfile.objects.select_related('User').all()
resource_name = 'entry'
fields = ['username','api_key','email','homeAddress']
#authorization = Authorization()
#authentication = MyAuthentication()
filtering = {
'api_key': ALL,
'homeAddress': ALL,
'email': ALL,
'query': ['icontains',],
}
def apply_filters(self, request, applicable_filters):
base_object_list …Run Code Online (Sandbox Code Playgroud) 我收到这个错误:
The object '' has an empty attribute 'posts' and doesn't allow a default or null value.
Run Code Online (Sandbox Code Playgroud)
我试图在帖子上获得"投票"的数量并将其返回到我的models.py中:
class UserPost(models.Model):
user = models.OneToOneField(User, related_name='posts')
date_created = models.DateTimeField(auto_now_add=True, blank=False)
text = models.CharField(max_length=255, blank=True)
def get_votes(self):
return Vote.objects.filter(object_id = self.id)
Run Code Online (Sandbox Code Playgroud)
这是我的资源:
class ViewPostResource(ModelResource):
user = fields.ForeignKey(UserResource,'user',full=True)
votes= fields.CharField(attribute='posts__get_votes')
class Meta:
queryset = UserPost.objects.all()
resource_name = 'posts'
authorization = Authorization()
filtering = {
'id' : ALL,
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
我用Tastypie-Django编写了一个API,我想用Backbone做一个网页来更简单地访问模型.我在Backbone中创建了一个这样的Model和一个这样的集合:
var Abstract = Backbone.Model.extend({
defaults : {
}
});
var AbstractCollection = Backbone.Collection.extend({
model: Abstract,
url : "http://192.168.0.195/api/v1/abstract/?format=json"
});
Run Code Online (Sandbox Code Playgroud)
它在View中的fetch方法就像这样:
var abs = new PocketsAbstractCollection();
abs.fetch({
success: function (collection, response) {
console.log(abs.length);
console.log(abs.models);
}
});
Run Code Online (Sandbox Code Playgroud)
问题是我从这个表单收到一个JSON:
{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 12}, "objects": [{ ... }]}
Run Code Online (Sandbox Code Playgroud)
当我在属性中看到集合的模型时,我有2个元素,一个元素和一个带有元素的对象数组.如何访问"对象数组"元素?
如果我写abs.attributes这给我一个错误.
attributes: Object
meta: Object
objects: Array[12]
0: Object
1: Object
2: Object
3: Object
4: Object
.
.
.
length: 12
Run Code Online (Sandbox Code Playgroud)
有人能帮我吗?
谢谢!!
我发送一个POST来创建一个新的简单Resource(不是ModelResource),并且可行.
我的问题是如何将创建的资源bundle属性恢复到ajax响应?
这是资源示例:
class MyResource(Resource):
x = fields.CharField(attribute='x')
y = fields.CharField(attribute='y')
class Meta:
resource_name = 'myresource'
object_class = XYObject
authorization = Authorization()
def obj_create(self, bundle, request=None, **kwargs):
x = bundle.data["x"]
x = bundle.data["y"]
bundle.obj = XYObject(x, y)
return bundle
Run Code Online (Sandbox Code Playgroud)
这是POST请求
$.ajax({
type: "POST",
url: '/api/v1/myresource/',
contentType: 'application/json',
data: data,
dataType: 'json',
processData: false,
success: function(response)
{
//get my resource here
},
error: function(response){
$("#messages").show('error');
}
});
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用tastypie实现一个带RESTful API的简单Django服务.我的问题是,当我尝试使用PUT创建WineResource时,它工作正常,但是当我使用POST时,它会返回HTTP 501错误.阅读tastypie文档,似乎应该只是工作,但事实并非如此.
这是我的api.py代码:
class CustomResource(ModelResource):
"""Provides customizations of ModelResource"""
def determine_format(self, request):
"""Provide logic to provide JSON responses as default"""
if 'format' in request.GET:
if request.GET['format'] in FORMATS:
return FORMATS[request.GET['format']]
else:
return 'text/html' #Hacky way to prevent incorrect formats
else:
return 'application/json'
class WineValidation(Validation):
def is_valid(self, bundle, request=None):
if not bundle.data:
return {'__all__': 'No data was detected'}
missing_fields = []
invalid_fields = []
for field in REQUIRED_WINE_FIELDS:
if not field in bundle.data.keys():
missing_fields.append(field)
for key in bundle.data.keys(): …Run Code Online (Sandbox Code Playgroud) 我使用"使用直通的ManyToManyField"的中间模型
通常,如果我不使用中间字段,m2m关系将是唯一的并且不能具有重复数据.
我使用中间模型后.m2m之间的关系可以有相同的数据.像这样
| | ['0'] (
| | | addToProfile => Array (0)
| | | (
| | | )
| | | endDate = NULL
| | | feedType = "N"
| | | id = 1
| | | info = "Big Kuy No Fear"
| | | likeMaker => Array (3)
| | | (
| | | | ['0'] = "/api/v2/user/2/"
| | | | ['1'] = "/api/v2/user/2/"
| | | | ['2'] = …Run Code Online (Sandbox Code Playgroud) 如何使用Tastypie基于日期时间字段范围过滤对象.
我有一个Post模型:
class Post(models.Model):
title = models.CharField(max_length=40)
postTime = models.DateTimeField(auto_now_add=True)
description = models.CharField(max_length=140)
Run Code Online (Sandbox Code Playgroud)
邮件对象通过Tastypie检索.我想要检索的对象范围是从今天创建的所有对象到3天前创建的所有对象.所以我尝试从查询集中过滤对象,如下所示
RecentPosts(ModelResource):
class Meta:
queryset= Post.objects.filter(postTime__range=(date.today(), date.today() -timedelta(days=3)))
resource_name = 'recent-posts'
fields = ['id','postTime']
authentication = BasicAuthentication()
authorization =DjangoAuthorization()
serializer = Serializer(formats=['json'])
include_resource_uri = False
filtering = {
'postTime': ALL,
'description': ALL,
}
Run Code Online (Sandbox Code Playgroud)
即使这样做后我也无法检索对象.我还能怎么做呢?