尝试将模型转换为字典时图像字段上的值错误

Value error on Image field when trying to comvert model to dict

我有 2 个模型,第一个是 Garage

class Garage(models.Model):
    name = models.CharField(verbose_name=_('Garage'), max_length=200)

    @property
    def cars(self) -> list:
        from django.forms.models import model_to_dict

        cars = []
        for i in Car.objects.filter(garage=self.id):
            cars.append(model_to_dict(i))

        return cars

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = _('Garage')

我的第二个模型是汽车,

class Car(models.Model):
    name = models.CharField(verbose_name=_('Car Name'), max_length=200)
    garage = models.ForeignKey(verbose_name=_('Garage'), to=Garage, on_delete=models.PROTECT)
    price = models.DecimalField(verbose_name=_('Price'), max_digits=10, decimal_places=2)
    image = models.ImageField(verbose_name=_('Select Image'), upload_to='cars/', default=None)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = _("Car")
        verbose_name_plural = _("Cars")

现在,当我尝试 运行 时,Garage 模型中的 属性 'cars' 抛出 ValueError。

ValueError: The 'image' attribute has no file associated with it.

完整的错误日志为:

Traceback (most recent call last):
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 145, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 143, in _get_response
    response = response.render()
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/template/response.py", line 106, in render
    self.content = self.rendered_content
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/response.py", line 72, in rendered_content
    ret = renderer.render(self.data, accepted_media_type, context)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/renderers.py", line 107, in render
    allow_nan=not self.strict, separators=separators
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/utils/json.py", line 28, in dumps
    return json.dumps(*args, **kwargs)
  File "/usr/lib/python3.7/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/usr/lib/python3.7/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.7/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/utils/encoders.py", line 67, in default
    return tuple(item for item in obj)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/utils/encoders.py", line 67, in <genexpr>
    return tuple(item for item in obj)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/files/base.py", line 78, in __iter__
    for chunk in self.chunks():
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/files/base.py", line 55, in chunks
    self.seek(0)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/files/utils.py", line 20, in <lambda>
    seek = property(lambda self: self.file.seek)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/db/models/fields/files.py", line 41, in _get_file
    self._require_file()
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/db/models/fields/files.py", line 38, in _require_file
    raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
ValueError: The 'image' attribute has no file associated with it.

我无法解决这个错误,我需要序列化图像字段。我该如何解决这个错误?

所以,我能够解决我的问题。我刚刚创建了一个 属性 并为汽车模型生成了图像 url。

汽车models.py

class Car(models.Model):
    name = models.CharField(verbose_name=_('Car Name'), max_length=200)
    garage = models.ForeignKey(verbose_name=_('Garage'), to=Garage, on_delete=models.PROTECT)
    price = models.DecimalField(verbose_name=_('Price'), max_digits=10, decimal_places=2)
    image = models.ImageField(verbose_name=_('Select Image'), upload_to='cars/', default=None)

    @property
    def image_url(self):
        from django.contrib.sites.models import Site

        domain = Site.objects.get_current().domain
        url = 'http://{domain}'.format(domain=domain)

        if self.image and hasattr(self.image, 'url'):
            return url + self.image.url

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = _("Car")
        verbose_name_plural = _("Cars")

并且刚刚将此 image_url 属性 包含在 model_to_dict 字段过滤器中。

model_to_dict(i, fields=[..., 'image_url', ...]