django-tastypie アプリには、次の Django モデルがあります。
class Car(models.Model):
name=models.CharField('name',max_length=64)
class CarTrack(models.Model):
car=models.ForeignKey(Car)
tdata=models.CharField('track data',max_length=255)
created = models.DateTimeField('created time',auto_now_add=True)
次のtastypieリソースを作成しました:
class CarRsc(ModelResource):
class Meta:
queryset=Car.objects.all()
resource_name='car'
authentication = Authentication()
authorization=Authorization()
class CarTrackRsc(ModelResource):
car=fields.ForeignKey(CarRsc, 'car')
class Meta:
queryset=Detection.objects.all()
resource_name='track'
authentication = Authentication()
authorization=Authorization()
def hydrate(self, bundle):
if not bundle.obj.pk:
bundle.obj.car=bundle.request.user.get_profile().car
return bundle
クライアントが新しい CarTrackRsc (例: {"tdata":"blablabla"}) を送信するときに、CarTrack の外部キーを特定の車に設定したいと考えています。上記の例では、ハイドレート メソッドをオーバーライドしてそれを実現しようとしています (現在のログイン ユーザーの車を取得することによって)。しかし、うまくいかないようでした。それは正しい方法ですか?Tastypie のドキュメントには、ハイドレート メソッドの使用方法の例が示されていますが、単純なフィールドに関するものであり、関連フィールド (外部キーなど) に関するヒントはありません。