Django串行化器数据

k10s72fa  于 2023-03-04  发布在  Go
关注(0)|答案(1)|浏览(148)

我需要在“title”而不是“id”中获取购物篮的值。
如何操作?如何使用ManyToManyField从另一个“Client”模型中的“Position”模型获取“title”的值?它会自动传输ID,并且需要“title”
我已经尝试了很多方法,但...这一定很容易,但我搜索信息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
]
}

我需要这样的东西-“篮子”:[“显示器”,“键盘”]

xxslljrj

xxslljrj1#

我找到了解决办法:

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]

不要向我扔西红柿,我只是在编程的方式开始:)
由于客户端表中的数据存储在ID中,因此需要使用get_position方法

相关问题