Tastypie api not showing ForeignKey as a result of json

I recently started using tastypie to open an api for a potential smartphone app.

I am using python-2.7 and Django-1.1.2

Two things confuse me.

1: in the EntryResource class when calling ForeignKey they just call the resource with the name resource_name, when I do it this way, I get the following trace.

 691. assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) Exception Type: AssertionError at /api/v1/activity-stream-item-subject/ Exception Value: ForeignKey(<class 'api.resources.UserResource'>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' 

2: if I change EntryResource to user = fields.ForeignKey(UserResource, 'user') , then it works fine without tracing, however, I don't see the related information in the JSON response.

api / resources.py

 class UserResource(ModelResource): class Meta: queryset = User.objects.all() resource_name = 'user' excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser'] filtering = { 'username': ALL, } class EntryResource(ModelResource): user = fields.ForeignKey(UserResource, 'user') class Meta: queryset = Entry.objects.all() resource_name = 'entry' authorization = Authorization() filtering = { 'user': ALL_WITH_RELATIONS, 'pub_date': ['exact', 'lt', 'lte', 'gte', 'gt'], } 

Any ideas?

+6
source share
2 answers

I'm not sure if I understand your first problem, but about the second, you need to indicate that you want to use the full resource using:

 user = fields.ForeignKey(UserResource, 'user',full=True) 

otherwise, you will get the resource URI instead of the content. ( Link )

Also just for reference, keep in mind that the requirements are:

Django 1.2+ (can work on Django 1.1)

+7
source

If you want to display all user fields as a result of json, you need to set full=True .

 user = fields.ForeignKey(UserResource,user,full=True) 
-2
source

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


All Articles