2017-12-28 11 views
1

カートアイテムが削除されると、カートアイテムをリフレッシュするためにajaxを使用しています。それはうまくいけば、もし私が画像で応答しなければ、エラーmethod object is not JSON serializableが出ます。画像部分にmodel_to_dictを使用すると、エラー'function' object has no attribute '_meta'が表示されます。ここメソッドオブジェクトはJSONシリアライズ可能ではありません

は、私は、このような問題を解決するにはどうすればよいmodel_to_dict

x.first_imageをラップしながら、私は'function' object has no attribute '_meta'エラーを取得するコード

def cart_detail_api_view(request): 
    cart_obj, new_obj = Cart.objects.new_or_get(request) 
    products = [{ 
      "id": x.id, 
      "url": x.get_absolute_url(), 
      "name": x.name, 
      "price": x.price, 
      "image": x.first_image 
      } 
      for x in cart_obj.furnitures.all()] 
    cart_data = {"products": products, "subtotal": cart_obj.sub_total, "total": cart_obj.total} 
    return JsonResponse(cart_data) 

class Furniture(models.Model): 
    name = models.CharField(max_length=100, blank=True, null=True) 
    manufacturer = models.ForeignKey(Manufacturer, blank=True, null=True) 
    slug = models.SlugField(max_length=200, unique=True) 

    def __str__(self): 
     return self.name 

    def first_image(self): 
     """ 
     Return first image of the furniture otherwise default image 
     """ 
     if self.furniture_pics: 
      return self.furniture_pics.first() 
     return '/static/img/4niture.jpg' 

class Cart(models.Model): 
    user = models.ForeignKey(User, null=True, blank=True) 
    furnitures = models.ManyToManyField(Furniture, blank=True) 

のですか?あなたが知っているよう

class FurniturePic(models.Model): 
    """ 
    Represents furniture picture 
    """ 
    furniture = models.ForeignKey(Furniture, related_name='furniture_pics') 
    url = models.ImageField(upload_to=upload_image_path) 

答えて

3

問題を更新し

は、である:

"image": x.first_image 

first_imageは、関数なので、JSONに変換することはできません。あなたがしたいことは、first_imageによって返された値をシリアル化することです。だから、そのために、あなたはコールこの機能する必要があります:

"image": x.first_image() # note the brackets 

また、私もで、別の問題に気づいた:だから

return self.furniture_pics.first() # will return the image object; will cause error 

、あなたはそれを変更する必要がありますTo:

return self.furniture_pics.first().url # will return the url of the image 

更新:

self.furniture_pics.first().urlは、ImageFieldであるFurniturePic.urlを返します。シリアライズのためには、その画像のURLが必要です。あなたはこれを行う必要があるだろう:あなたが見ることができるように、これは混乱の元になっている

return self.furniture_pics.first().url.url # call url of `url` 

FurniturePic.urlフィールドの名前をFurniturePic.imageに変更することをおすすめします。しかし、それを無視して自由に感じてください。

+0

このようにして、 'Object of type 'FurniturePic'はJSONのシリアライザブルではありません。私は1つの質問で異なる種類のエラーを表示することをためらった:) – pri

+0

また試みたx.first_image()。URL 'を投げた'タイプのオブジェクト 'ImageFieldFile'はJSONのシリアル化可能ではない 'このエラー – pri

+0

は' self.furniture_picsではない。 first()。url' 'x.first_image()。url'と同じですか? – pri

関連する問題