我需要在'title'而不是'id'中获得篮子的价值。
我该怎么做?如何使用 ManyToManyField 从另一个“客户端”模型中的“位置”模型获取“标题”的值。它会自动传输 ID 并且需要“标题”
我试过很多方法但是...一定很简单,但是我搜索信息2天
class Position(models.Model):
title = models.CharField(max_length=150, verbose_name='Title')
slug = models.SlugField(max_length=100, unique=True, db_index=True, verbose_name='URL')
description = models.CharField(max_length=500, verbose_name='Describe')
photo = models.ImageField(upload_to="photos/%Y/%m/", verbose_name='Photo', null=True)
price = models.DecimalField(decimal_places=2, max_digits=10, verbose_name='Price')
date_create = models.DateTimeField(auto_now_add=True, verbose_name='Date create')
date_update = models.DateTimeField(auto_now=True, verbose_name='Date update')
is_published = models.BooleanField(default=True, verbose_name='Is published')
in_stock = models.BooleanField(default=True, verbose_name='In stock')
class Client(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
basket = models.ManyToManyField('Position', default=None, blank=True, related_name='basket')
def __str__(self):
return f'{self.user.username}, id-{self.user.id}'
class ClientSerializer(serializers.ModelSerializer):
class Meta:
model = Client
fields = "__all__"
class ClientViewSet(viewsets.ModelViewSet):
serializer_class = ClientSerializer
permission_classes = (IsOwnerOrReadOnly,)
def get_queryset(self):
pk = self.kwargs.get('pk')
# need a list of objects, not an one
return Client.objects.filter(pk=pk)
结果:
{
"id": 1,
"user": 1,
"basket": [
1
]
}
需要这样的东西 - “篮子”:['显示器','键盘']
您可以使用 PositionSerializer 获取 Client 篮子 ManyToManyField 中每个 Position 对象的标题。
class PositionSerializer(serializers.ModelSerializer):
class Meta:
model = Position
fields = ('title',)
class ClientSerializer(serializers.ModelSerializer):
basket = PositionSerializer(many=True, read_only=True)
class Meta:
model = Client
fields = "__all__"
我找到了解决方案:
class ClientSerializer(serializers.ModelSerializer):
# need to get title from Position, not id
basket = serializers.SerializerMethodField(method_name='get_position')
class Meta:
model = Client
fields = "__all__"
def get_position(self, obj):
list = Client.objects.get(id=obj.id).basket.all()
return [position.title for position in list]
不要向我扔西红柿,我只是在编程方式的开始:)
需要使用get_position方法是因为Client-table中的数据 存储在 Id