I want save the category and their subcategories to the database and here each category have a multiple subcategories.Could you please help me to save the user,category and multiple subcategories corresponding to category.Models.py , Serializers.py, Views.py and incomming request is attached.
Models.py
class SavingCategoryandPreferences(models.Model):
user = models.ForeignKey(User, related_name='user')
news_category = models.ForeignKey(NewsCategory)
subcategories= models.ManyToManyField(NewsSubCategory, related_name='sub')
sort_order = models.IntegerField(default=0)
slug = AutoSlugField(populate_from='subcategories_id', separator='', editable=True)
created_time = models.DateTimeField("Created Date", auto_now_add=True)
Serializers.py
class MobilecatsubSerializer(serializers.ModelSerializer):
class Meta:
model = SavingCategoryandPreferences
fields = ('id', 'user', 'subcategories', 'news_category',)
Views.py
class MobileCatsubViewswt(viewsets.ModelViewSet):
serializer_class = serializers.MobilecatsubSerializer
queryset = SavingCategoryandPreferences.objects.all()
Incomming Request
{
"user":"39",
"news_category":"22",
"subcategories": [
{"sub_id":"1"},
{"sub_id":"2"}
]
}
ForeignKey
is many-to-one, so multiple instances ofSavingCategoryandPreferences
can be related to only oneNewsSubCategory
instance. You should fix your model schema first before moving forward."subcategories": [1, 2]
instead, you could just use aPrimaryKeyRelatedField
in your serializer.