2011-08-03 29 views
6

Gần đây tôi đã bắt đầu sử dụng tastypie để mở api của tôi cho một ứng dụng điện thoại thông minh tiềm năng.api ngon không hiển thị ForeignKey trong kết quả json

Tôi đang sử dụng python-2,7 và Django-1.1.2

Hai điều đang bối rối tôi

1: trong lớp EntryResource khi gọi ForeignKey, họ chỉ cần gọi các nguồn lực cùng với resource_name, khi tôi thực hiện theo cách như vậy, tôi nhận được truy nguyên sau.

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: nếu tôi thay đổi EntryResource-user = fields.ForeignKey(UserResource, 'user'), sau đó nó chạy tốt mà không có một traceback, tuy nhiên tôi không thể nhìn thấy các thông tin liên quan trong phản ứng JSON.

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'], 
     } 

Bất kỳ ý tưởng?

Trả lời

7

Tôi không chắc chắn nếu tôi hiểu vấn đề đầu tiên của bạn, nhưng về thứ hai, bạn sẽ cần phải xác định bạn muốn tài nguyên đầy đủ sử dụng:

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

nếu không bạn sẽ nhận được các tài nguyên URI thay vì nội dung. (Ref)

Cũng chỉ để tham khảo, cần lưu ý rằng các yêu cầu nhà nước:

Django 1.2+ (Có thể làm việc trên Django 1,1)

-2

Nếu bạn muốn hiển thị tất cả các lĩnh vực Người dùng trong kết quả json, bạn phải đặt full=True.

user = fields.ForeignKey(UserResource,user,full=True) 
+0

đúng là không hợp lệ python – josephmisiti

Các vấn đề liên quan