A
A
astatium1352020-09-09 18:37:02
Django
astatium135, 2020-09-09 18:37:02

How to create a fake field in a django model?

There is a simple class

class Image(models.Model):
  user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
  name = models.TextField(verbose_name="базовое имя изображения")
  base_image = models.ImageField(verbose_name="базовое изображение")
  resize_image = models.ImageField(verbose_name="изменённое изображение", blank=True, null=True)
  class Meta:
    verbose_name = "изображение"
    verbose_name_plural = "изображения"
  def __str__(self):
    return self.name

It is necessary to add calculated "fake" fields, which, if not reflected in the database, would nevertheless be perceived by django as normal models.Field, i.e. were available in the admin panel, were given by graphen without a tambourine, etc. Something like
def get_image(self) -> str:
  if self.resize_image:
    return self.resize_image
  else:
    return self.base_image
image = property(get_image)
, only working.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-09-09
@bacon

The method without parameters is normally shown in the admin panel, you don't even need to make it property https://docs.djangoproject.com/en/3.1/ref/contrib/... what's wrong with graphen, no idea.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question