如何在 Django 模型文本字段中创建、获取和更新 JSON 数据?

How to Create ,Get and update JSON data in Django model Text field?

我看到很多与此问题相关的答案,但我不知道如何实现它。

我的要求是:

(创建)首先使用键和值创建数据: {"pradip" : 80} 并存储在 user_rate_details 模型字段中。

(更新)第二次在此字段中追加新数据: {"pradip" : 80,"exz" : 70} 并保存。 在我看来如何实现这一目标..

models.py:

    class UserPhoto(models.Model):
        user = models.ForeignKey(to = User,on_delete = models.CASCADE,related_name='userPhoto')
        ......
        rated_by = models.ManyToManyField(Profile,blank=True,related_name='rate_by')
        <b>user_rate_details = models.TextField()  ⬅⬅⬅⬅⬅ Here store JSON data</b>
        created_date = models.DateTimeField(auto_now_add=True)</pre>

views.py:

    class PhotoRate(APIView):
        permission_classes = [IsAuthenticated]
        
        def get_userPhoto(self,pk):
            try:
                return UserPhoto.objects.get(id = pk)
            except UserPhoto.DoesNotExist:
                raise Http404
        
        def post(self,request,formate = None):
            pk = request.data.get('photo_id')
            rate = request.data.get('rate')
            <b>photo = self.get_userPhoto(pk)
            ???????? How to create or update Json data here???
            return Response(??JSON DATA??)</b></pre>

你知道的任何其他最好的方法请告诉我..

谢谢..

在模型中创建文本字段并转储或加载 JSON 数据..

models.py:

    import json
    class UserPhoto(models.Model):
        user = models.ForeignKey(to = User,on_delete = models.CASCADE,related_name='userPhoto')
        ......
        rated_by = models.ManyToManyField(Profile,blank=True,related_name='rate_by')
        <b>user_rate_details = models.TextField(default="{}")</b>
        created_date = models.DateTimeField(auto_now_add=True)
    
        <b>@property
        def rate_details(self):
            return json.loads(self.user_rate_details)</b></pre>

views.py:

class PhotoRate(APIView):
    permission_classes = [IsAuthenticated]
    
    def get_userPhoto(self,pk):
        try:
            return UserPhoto.objects.get(id = pk)
        except UserPhoto.DoesNotExist:
            raise Http404
    
    def post(self,request,formate = None):
        pk = request.data.get('photo_id')
        rate = request.data.get('rate')
        photo = self.get_userPhoto(pk)
        <b>user_dict = photo.rate_details
        user_dict[self.request.user.username] = int(rate)
        <b>photo.user_rate_details = json.dumps(user_dict)</b>
        photo.save(update_fields=['user_rate_details'])</b>
        return Response({"Success" : "Rate submited!!"},status=status.HTTP_200_OK)

    def patch(self,request,formate=None):
        pk = request.data.get('photo_id')
        photo = self.get_userPhoto(pk)
        <b>rate_detail = photo.rate_details</b>
        return Response({"Rated Users" : rate_detail},status=status.HTTP_200_OK)</pre>
		

我真的不明白你的问题,但如果你打算在你的模型字段中存储 json 数据,那么你可以尝试...

在您的模型中:

import json

@property
def user_rate_details(self):
     return json.loads(self.user_rate_details)

在您看来:

pk = request.data.get('photo_id')
rate = request.data.get('rate')
photo = self.get_userPhoto(pk)
details = photo.user_rate_detail
details['rate'] = int(rate)
photo.user_rate_details = json.dumps(details)
photo.save(update_fields=['user_rate_details'])
return Response()