就像回報的Youtube「新領域」,我想看看哪些類別我的文章(裝)在。
我的方法是...
- 獲取類別的整個列表屬於用戶
- 獲取類別的整個列表屬於用戶和後
- 對它們進行比較,並返回JSON
建立一個Seriailizer時,我覺得我完全是股票。所以frustraing ... :(
請隨時免費,如果您有任何更好的想法來改變我的做法。
預期JSON outputis下面
{
...
"categories": [
{
"id": 1,
"name": "asd"
"added": True <- since the post is added to 'asd'
},
{
"id": 2,
"name": "workout"
"added": True
},
...
{
"id": 5,
"name": "bgm"
"added": False <- since the post is not added to 'bgm'
},
]
}
這裏是views.py
class OutfitDetailView(generics.RetrieveAPIView):
queryset = Outfit.objects.all()
serializer_class = OutfitDetailSerializer
lookup_field = 'pk'
這裏是serializers.py(這是一個問題)
class OutfitDetailSerializer(serializers.ModelSerializer):
...
def get_categories(self, obj):
# Right Here! Get whole categories associated with user
all_categories = Category.objects.filter(owner=self.context['request'].user)
# And the categories associated with user AND the post
categories = obj.categories.filter(owner=self.context['request'].user)
return CategorySerializer(categories, many=True).data
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = (
'id',
'name',
'added' <- here I want to add 'added' field but I don't know how.
)
如果你需要一個模型
class Outfit(models.Model):
...
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
content = models.CharField(max_length=30)
...
class Category(models.Model):
name = models.CharField(max_length=20)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
outfits = models.ManyToManyField(Outfit, related_name="categories", blank=True)
main_img = models.ImageField(
upload_to=upload_location_category,
null=True,
blank=True)
...
總是加上'True'? –
我剛剛在JSON部分添加了更多描述。 @BearBrown感謝您指出 –
@BearBrown讓我知道如果有什麼不清楚 –