2016-10-26 19 views
0

私はユーザーのための警告システムを持っています。ユーザーはカテゴリを購読することができ、それに基づいて私は警告を生成します。Django Rest外部キー値の設定

私はこのようなアラートのモデルを定義しました。

class City(models.Model): 
    name = models.CharField(max_length=25) 

    def __unicode__(self): 
     return self.name 


class Area(models.Model): 
    name = models.CharField(max_length=25) 
    city = models.ForeignKey(City) 

    def __unicode__(self): 
     return self.name 


class Category(models.Model): 
    name = models.CharField(max_length=25) 

    def __unicode__(self): 
     return self.name 


class SubscribeAlert(models.Model): 
    category = models.ForeignKey(Category) 
    user = models.ForeignKey(settings.AUTH_USER_MODEL) 
    status = models.BooleanField(default=False) 
    attributes = JSONField('Subscriptions', null=True, blank=True) 


class SubscribeLocation(models.Model): 
    subscribe = models.ForeignKey(SubscribeAlert) 
    area = models.ForeignKey(Area) 

通知のために、カテゴリを選択して複数の領域を選択できます。 これは私のモデル構造ですか?

また、ModelSerializerの残りの部分を定義する方法は、SubscribeAlertと多くのSubscribeLocationを同時に挿入することです。

class NotifyCreateSerializer(ModelSerializer): 
    class Meta: 
     model = SubscribeAlert 

サブスクリプションを作成するにはどうすれば拡張できますか?

ありがとうございます。

答えて

1

nested serializersを使用する必要があります。ここに例がある(動作しないかもしれない)

class SubscribeLocationSerializer(ModelSerializer): 
    class Meta: 
     model = SubscribeLocation 

class NotifyCreateSerializer(ModelSerializer): 
    subscribelocation_set = SubscribeLocationSerializer(many=True) 
    class Meta: 
     model = SubscribeAlert 
     fields = ('category', 'user', 'status', 'attributes', 
        'subscribelocation_set') 
+0

"無効なデータですが、辞書が必要ですが、intを取得しました。"私はこのようにエリアIDを渡します。 –

+0

{ "カテゴリ":1、 "ユーザ":1、 "ステータス":偽、 は、 "属性":ヌル、 "subscribelocation_setを":[1,2,3] }とSubscribeAlertをマッピングする方法この? –

+0

'subscribeelocation_set'にはdictsを含める必要があります。 "subscribelocation_set":[{data1}、{data2}] –

関連する問題