I have the tastypie resource:
class ProjectPermissionResource(ModelResource):
project = fields.ToOneField(ProjectResource, 'project', full=True, readonly=True)
...
As you see, the project resource is returning full with all fields.
I need to remove some fields, so I tried to use the dehydrate_project method:
def dehydrate_project(self, bundle):
# delete some project fields here
return bundle
But after adding this method I get "maximum recursion depth exceeded while calling a Python object". Stucked after this.
Need to delete some fields from project (in details I need only ot id, name and so on...)
You can construct your own object from bundle.data
So basically something like this:
return bundle.data = {stuffs}
Related
I have a model named package in an app named exam.
I use Django rest framework and have the following View:
class PackageListCreaet(ListCreateAPIView):
queryset = Package.objects.all()
serializer_class = PackageSerializer
permission_classes = (IsAdminAndReadOnlyForStaff,)
#method_decorator(rest_error_decorator(logger))
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
and the following serializer:
class PackageSerializer(serializers.ModelSerializer):
class Meta:
model = Package
fields = ('pk','name','price','exams','active')
when I try creating a new package from Django admin it works just fine.
But when I try creating a new package using the API above it throws the following error:
duplicate key value violates unique constraint \"exam_package_pkey\"\nDETAIL: Key (id)=(1) already exists
And it's worth mentioning that although I get this error the object gets created.(and so the "(id)=(1) number changes each time".)
I looked around a bit to find a solution and realized the problem is that the id field of exam_package table is out of sync. I tried syncing it like this and it didn't work.
Then I tried removing all records (which happened with no error) and setting the primary key to 1 like this. And it still doesn't work.
I looked into this link and realized maybe my probmlem is the same and maybe DRF is creating two new instances which is why I get the error. But I have no idea how to fix it.
Why is pk int the fields list? Probably this is the problem, when you are creating a Package via API you are passing 1 as pk. Try to add pk to the property read_only_fields
read_only_fields = ('pk',)
So you don't need it when you create a Package via API.
Working with Google App Engine for Python, I am trying to create and then update an ndb entity. To update a single property, you can just access the property using a dot, e.g.
post.body = body
But I would like to know if there is a simple way to update multiple fields within an ndb entity. The following code:
class Create(Handler):
def post(self):
## code to get params
post = Post(author = author,
title = title,
body = body)
post.put()
class Update(Handler):
def post(self, post_id):
post = post.get_by_id(int(post_id))
fields = ['author', 'title', 'body']
data = get_params(self.request, fields)
for field in fields:
post[field] = data[field]
post.put()
The "Create" handler works fine, but the "Update" handler results in:
TypeError: 'Post' object does not support item assignment
So it seems I would need to access the properties using a dot, but that is not going to work when I have a list of properties I want to access.
Can someone provide an alternative way to update multiple properties of an NDB entity after it has been created?
You should use setattr.
for field in fields:
setattr(post, field, data[field])
(Note that GAE objects do actually provide a hidden way of updating them via a dict, but you should use the public interface.)
You can use the populate method:
post.populate(**data)
So far I'm extremely happy with Django Rest Framework, which is why I alsmost can't believe there's such a large omission in the codebase. Hopefully someone knows of a way how to support this:
class PinSerializer(serializers.ModelSerializer):
item = ItemSerializer(read_only=True, source='item')
item = serializers.IntegerSerializer(write_only=True)
class Meta:
model = Pin
with the goal
The goal here is to read:
{pin: item: {name: 'a', url: 'b'}}
but to write using an id
{pin: item: 10}
An alternative would be to use two serializers, but that looks like a really ugly solution:
django rest framework model serializers - read nested, write flat
Django lets you access the Item on your Pin with the item attribute, but actually stores the relationship as item_id. You can use this strategy in your serializer to get around the fact that a Python object cannot have two attributes with the same name (a problem you would encounter in your code).
The best way to do this is to use a PrimaryKeyRelatedField with a source argument. This will ensure proper validation gets done, converting "item_id": <id> to "item": <instance> during field validation (immediately before the serializer's validate call). This allows you to manipulate the full object during validate, create, and update methods. Your final code would be:
class PinSerializer(serializers.ModelSerializer):
item = ItemSerializer(read_only=True)
item_id = serializers.PrimaryKeyRelatedField(write_only=True,
source='item',
queryset=Item.objects.all())
class Meta:
model = Pin
fields = ('id', 'item', 'item_id',)
Note 1: I also removed source='item' on the read-field as that was redundant.
Note 2: I actually find it rather unintuitive that Django Rest is set up such that a Pin serializer without an Item serializer specified returns the item_id as "item": <id> and not "item_id": <id>, but that is beside the point.
This method can even be used with forward and reverse "Many" relationships. For example, you can use an array of pin_ids to set all the Pins on an Item with the following code:
class ItemSerializer(serializers.ModelSerializer):
pins = PinSerializer(many=True, read_only=True)
pin_ids = serializers.PrimaryKeyRelatedField(many=True,
write_only=True,
source='pins',
queryset=Pin.objects.all())
class Meta:
model = Item
fields = ('id', 'pins', 'pin_ids',)
Another strategy that I previously recommended is to use an IntegerField to directly set the item_id. Assuming you are using a OneToOneField or ForeignKey to relate your Pin to your Item, you can set item_id to an integer without using the item field at all. This weakens the validation and can result in DB-level errors from constraints being violated. If you want to skip the validation DB call, have a specific need for the ID instead of the object in your validate/create/update code, or need simultaneously writable fields with the same source, this may be better, but I wouldn't recommend anymore. The full line would be:
item_id = serializers.IntegerField(write_only=True)
If you are using DRF 3.0 you can implement the new to_internal_value method to override the item field to change it to a PrimaryKeyRelatedField to allow the flat writes. The to_internal_value takes unvalidated incoming data as input and should return the validated data that will be made available as serializer.validated_data. See the docs: http://www.django-rest-framework.org/api-guide/serializers/#to_internal_valueself-data
So in your case it would be:
class ItemSerializer(ModelSerializer):
class Meta:
model = Item
class PinSerializer(ModelSerializer):
item = ItemSerializer()
# override the nested item field to PrimareKeyRelatedField on writes
def to_internal_value(self, data):
self.fields['item'] = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all())
return super(PinSerializer, self).to_internal_value(data)
class Meta:
model = Pin
Two things to note: The browsable web api will still think that writes will be nested. I'm not sure how to fix that but I only using the web interface for debug so not a big deal. Also, after you write the item returned will have flat item instead of the nested one. To fix that you can add this code to force the reads to use the Item serializer always.
def to_representation(self, obj):
self.fields['item'] = ItemSerializer()
return super(PinSerializer, self).to_representation(obj)
I got the idea from this from Anton Dmitrievsky's answer here: DRF: Simple foreign key assignment with nested serializers?
You can create a Customized Serializer Field (http://www.django-rest-framework.org/api-guide/fields)
The example took from the link:
class ColourField(serializers.WritableField):
"""
Color objects are serialized into "rgb(#, #, #)" notation.
"""
def to_native(self, obj):
return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue)
def from_native(self, data):
data = data.strip('rgb(').rstrip(')')
red, green, blue = [int(col) for col in data.split(',')]
return Color(red, green, blue)
Then use this field in your serializer class.
I create a Field type that tries to solve the problem of the Data Save requests with its ForeignKey in Integer, and the requests to read data with nested data
This is the class:
class NestedRelatedField(serializers.PrimaryKeyRelatedField):
"""
Model identical to PrimaryKeyRelatedField but its
representation will be nested and its input will
be a primary key.
"""
def __init__(self, **kwargs):
self.pk_field = kwargs.pop('pk_field', None)
self.model = kwargs.pop('model', None)
self.serializer_class = kwargs.pop('serializer_class', None)
super().__init__(**kwargs)
def to_representation(self, data):
pk = super(NestedRelatedField, self).to_representation(data)
try:
return self.serializer_class(self.model.objects.get(pk=pk)).data
except self.model.DoesNotExist:
return None
def to_internal_value(self, data):
return serializers.PrimaryKeyRelatedField.to_internal_value(self, data)
And so it would be used:
class PostModelSerializer(serializers.ModelSerializer):
message = NestedRelatedField(
queryset=MessagePrefix.objects.all(),
model=MessagePrefix,
serializer_class=MessagePrefixModelSerializer
)
I hope this helps you.
I have the following model
class Open(models.Model):
name=models.TextField()
opened=models.DateTimeField(auto_now_add=True)
user=models.ForeignKey(User)
and the following resources
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
class OpenResource(ModelResource):
user = fields.ForeignKey(UserResource,'user')
class Meta:
queryset = Open.objects.all()
resource_name = 'open'
I'm trying to delete an Open object from some User's open_set.
For posting, I use the following code (using Requests):
content={"name":file_path,
"user":"/api/v1/user/2/"}
requests.post(
url='http://localhost:8000/api/v1/open/',
data=json.dumps(content),
headers={'content-type':'application/json'},
)
which works perfectly and does exactly what I want.
However, when trying to use similar code for deleting:
content={"name":file_path,
"user":"/api/v1/user/2/"}
requests.delete(
url='http://localhost:8000/api/v1/open/',
data=json.dumps(content),
headers={'content-type':'application/json'},
)
it just deletes all the Open objects from that user (in this case, user with id=2), instead of deleting only the Open objects whose "name" is file_path and whose "user" is "/api/vi/user/2/"
What am I missing?
Distinction between list and detail.
The RESTful methods are split into two kinds:
detail (for GET, PUT and DELETE):
/api/v1/objects/1/
and list (for GET, PUT and DELETE):
/api/v1/objects/
POST and PATCH are bit different.
Means that DELETE /api/v1/objects/ will remove all objects.
To delete one object you have to provide path with id:
DELETE /api/v1/objects/1/
Link to documentation
How filtering works in Tastypie:
You cannot just add things to content and wish to be picked up by Tastypie. All not meant to be there information will be ignored by Tastypie.
If you want to filter your list use queryset parameters:
/api/v1/objects/?name=asdfasdf&user=2
And allow filtering of these:
from tastypie.constants import ALL, ALL_WITH_RELATIONS
class Open(models.Model):
name=models.TextField()
opened=models.DateTimeField(auto_now_add=True)
user=models.ForeignKey(User)
filtering = {'name': ALL, 'user': ALL_WITH_RELATIONS}
After these changes you will be able to delete set of objects:
DELETE /api/v1/objects/?name=asdfasdf&user=5
Link to documentation
Edit:
So your call will look like this:
import urllib
content={"name":file_path,
"user":"/api/v1/user/2/"} # If doesn't work change '/api/v1/user/2/' into 2 I am not sure about this
url = 'http://localhost:8000/api/v1/open/?' + urllib.urlencode(content)
requests.delete(
url=url,
data=None,
headers={'content-type':'application/json'},
)
I am using Tastypie for non-ORM data source (Amazon Dynamodb). I have gone through the official documentation for non-ORM source and found the following code:
class MessageResource(Resource):
# Just like a Django ``Form`` or ``Model``, we're defining all the
# fields we're going to handle with the API here.
uuid = fields.CharField(attribute='uuid')
user_uuid = fields.CharField(attribute='user_uuid')
message = fields.CharField(attribute='message')
created = fields.IntegerField(attribute='created')
I am new to Tastypie and what I understand is that fields uuid, message, created.. which are returned by API are defined over here. Is there any way that I return those fields that are not defined here i.e. all those fields returned by the dictionary in obj_get_list or obj_get.
You can use the dehydrade method. Simply add a new key to bundle.data.
def dehydrate(self, bundle):
for item in bundle.obj.iteritems():
bundle.data["new_key"] = "new_value"
return bundle