Подтвердить что ты не робот

Django Tastypie создает новый ресурс с внешними ключами?

Я пытаюсь создать новые экземпляры с работой Tastypie, но я продолжаю получать эту ошибку с помощью внешних ключей. Вот мои вещи:

Модели:

class SuggestionVote(models.Model):
    created_by_user = models.ForeignKey(User)
    date_created = models.DateTimeField(auto_now_add = True)
    suggestion = models.ForeignKey(Suggestion)

class Suggestion(models.Model):
    title = models.TextField(blank=True,null=True)
    created_by_user = models.ForeignKey(User)
    date_created = models.DateTimeField(auto_now_add = True)
    votes = models.IntegerField(default=0)    

    def __unicode__(self):
        return self.title

Ресурсы модели (я использую свой собственный метод проверки подлинности):

class UserResource(ModelResource):
    class Meta:
        list_allowed_methods = ['get']
        queryset = User.objects.all()
        resource_name = 'user'
        authentication = MyBasicAuthentication()
        authorization = DjangoAuthorization()
class SuggestionResource(ModelResource):
    class Meta:
        list_allowed_methods = ['get']
        queryset = Suggestion.objects.all()
        resource_name = 'suggestion'
        authentication = MyBasicAuthentication()
        authorization = DjangoAuthorization()

class SuggestionVoteResource(ModelResource):
    class Meta:
        list_allowed_methods = ['get', 'post']
        detail_allowed_methods = ['get', 'post', 'put', 'delete']
        queryset = SuggestionVote.objects.all()
        resource_name = 'suggestionvote'
        authentication = MyBasicAuthentication()
        authorization = DjangoAuthorization()

Мой API-вызов с использованием jQuery:

var data = JSON.stringify({
    "suggestion": "/api/suggestion/1/",
    "created_by_user": "/api/user/1/"
});

$.ajax({
  url: 'http://127.0.0.1:8000/api/suggestionvote/',
  type: 'POST',
  contentType: 'application/json',
  data: data,
  dataType: 'json',
  processData: false
});

И ошибка, которую я получаю:

(1048,\ "Столбец 'created_by_user_id' не может быть null \" )

Я что-то пропустил?

4b9b3361

Ответ 1

Я думаю, что вам нужно определение поля отношений, что-то вроде этого должно работать:

from tastypie import fields

class SuggestionResource(ModelResource):
    # the relationship 
    created_by_user = fields.ToOneField( UserResource, 'created_by_user', full = True )

    class Meta:
        list_allowed_methods = ['get']
        queryset = Suggestion.objects.all()
        resource_name = 'suggestion'
        authentication = MyBasicAuthentication()
        authorization = DjangoAuthorization()

Я проверил и без аналогичного определения поля получаю ошибку точно так же, как ваша.

Ответ 2

Это тоже работает. Как поясняется здесь в Tastypie Tutorial

from tastypie import fields

class SuggestionResource(ModelResource):
    # the relationship 
    created_by_user = fields.ForeignKey( UserResource, 'created_by_user')

    class Meta:
        list_allowed_methods = ['get']
        queryset = Suggestion.objects.all()
        resource_name = 'suggestion'
        authentication = MyBasicAuthentication()
        authorization = DjangoAuthorization()