2017-10-31 5 views
2

の属性の代わりにcategory名とsubcategory名を取得する、私は自分のIDを取得し、のForeignKeyを表示することは、私が実際にこのような何かしたい私は、APIを実行すると、DRF

[ 
    { 
     "id": 1, 
     "name": "StrawBerry", 
     "category": 1, 
     "subcategory": 1 
    } 
] 

[ 
    { 
     "id": 1, 
     "name": "StrawBerry", 
     "category": "Fruits", 
     "subcategory": "Berries" 
    } 
] 

注意を:私はすでにカテゴリとサブカテゴリを持っています。私はそれらにアクセスする方法を知りたいだけです。一つの解決策は次のようになり

models.py

from django.db import models 

class Category(models.Model): 
    category = models.CharField(max_length=200) 
    parent = models.ForeignKey('self', blank=True, null=True, related_name='children') 

    class Meta: 
     unique_together = ('parent' , 'category') 

    def __str__(self): 
     return self.category 

class SubCategory(models.Model): 
    subcategory = models.CharField(max_length=200) 
    category = models.ForeignKey('Category', null=True, blank=True) 
    parent = models.ForeignKey('self', blank=True, null=True, related_name='subchilren') 

    class Meta: 
     unique_together = ('parent' , 'subcategory') 

    def __str__(self): 
     return self.subcategory 

class Product(models.Model): 
    name = models.CharField(max_length=200) 
    category = models.ForeignKey('Category', null=True, blank=True) 
    subcategory = models.ForeignKey('SubCategory', null=True, blank=True) 

    def __str__(self): 
     return self.name 

serializers.py

class GetProductSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Product 
     fields = ('id', 'name', 'category', 'subcategory') 

views.py

class GetProductViewSet(viewsets.ModelViewSet): 
    serializer_class = GetProductSerializer 
    queryset = Product.objects.all() 

答えて

1

StringRelatedField may be used to represent the target of the relationship using its unicode method.

http://www.django-rest-framework.org/api-guide/relations/#stringrelatedfield

あるいは、同様に、SlugRelatedFieldsとして:

SlugRelatedField may be used to represent the target of the relationship using a field on the target.

http://www.django-rest-framework.org/api-guide/relations/#slugrelatedfield

+0

それは私がいないM、働いていないStringRelatedFieldsとしてあなたGetProductSerializercategorysubcategoryフィールドを定義しますそれはどうしてそうですか?私のコードでそれを編集できますか? これは大きな助けになるでしょう。ありがとう! –

+0

どのように動作していないのか詳細を教えていただけますか?何らかのエラーが発生していますか? – souldeux

+0

'serializers.py'で' category = serializers.StringRelatedField(many = True) 'を使用しました。このエラーは' TypeError: 'Category' object is iterable'です。 –

関連する問題