You cannot exclude ForeignKey fields for a user in a piston

I have this model:

# models.py from django.contrib.auth.models import User class Test(models.Model): author = models.ForeignKey(User, related_name="tests") title = models.CharField(_("title"), max_length=100) 

Then in the api folder for the django piston web service:

 class TestHandler(BaseHandler): allowed_methods = ("GET") model = Test fields = ("title", ("author", ("username",))) def read(self, request, id): base = self.model.objects try: r = base.get(pk=id) return r except: return rc.NOT_FOUND 

If I call this web service, I get:

 { "title": "A test" "author": { "username": "menda", "first_name": "", "last_name": "", "is_active": true, "is_superuser": true, "is_staff": true, "last_login": "2011-02-09 10:39:02", "password": "sha1$83f15$feb85449bdae1a55f3ad5b41a601dbdb35c844b7", "email": " b@a.as ", "date_joined": "2011-02-02 10:49:48" }, } 

I also tried using exclude , but it doesn't work either.

How can I get only the username for author ? Thanks!

+4
source share
2 answers

Ok, so the problem is that Piston uses the set of fields defined in the User model by another Handler class, rather than the nested fields specified here.

Another user relates to the same problem in the piston discussion group:

http://groups.google.com/group/django-piston/browse_thread/thread/295de704615ee9bd

The problem seems to be caused by an error in the Piston serialization code. According to the documentation:

Using the model in the handler, Piston will remember the field / exception directives and use them in other handlers that return objects of this type (if not overridden.)

That all is well, except that the "(if not overridden.)" Case does not seem to be handled correctly.

I think a little modification to emitters.py can fix the problem (lines 160-193) ...

 if handler: fields = getattr(handler, 'fields') if not fields or hasattr(handler, 'fields'): ...dostuff... else: get_fields = set(fields) 

What should (maybe?) Read

 if fields: get_fields = set(fields) else: if handler: fields = getattr(handler, 'fields') ...dostuff... 

If you decide to try the emitters.py fix, let me know if this is a trick - it would be nice if it were fixed in django-piston.

Hooray!

+2
source

I think that you unnecessarily insert the author field.

It looks like your field attribute should read:

 fields = ("title", "author", ("username",)) 

From piston documents ...

 class UserHandler(BaseHandler): model = User fields = ('name', 'posts', ('title', 'date')) will show the title and date from a users posts. 
0
source

Source: https://habr.com/ru/post/1339006/


All Articles