1👍
✅
The current validated answer is sub-optimal since it results in 2 SQL queries.
You should rather modify your queryset as follow:
queryset = Question.objects.select_related('owner').all()
This way the ‘owner’ data is joined in one single SQL query.
4👍
Ah… got it figured out now. What worked:
class QuestionResource(ModelResource):
owner = fields.ForeignKey(UserResource, 'owner')
class Meta:
queryset = Question.objects.all()
allowed_methods = ['get','post']
fields = ['title','type']
resource_name = 'question'
include_resource_uri = True
serializer = PrettyJSONSerializer()
authentication = BasicAuthentication()
authorization = Authorization()
def hydrate(self, bundle, request=None):
bundle.obj.owner = User.objects.get(pk = bundle.request.user.id)
return bundle
I needed bundle.request.user.id rather than just request.user.id. Perhaps the other question I was looking at referred to an older version of TastyPie – seems older versions didn’t have request accessible in the bundle?
- [Django]-How to localize datetime in Django view code (with BST)?
- [Django]-Django, ImportError: cannot import name 'task' from 'celery'
- [Django]-Django replica data save to many databases
- [Django]-Test failures ("no transaction is active") with Ghost.py
Source:stackexchange.com