L
L
larionov_n2015-07-11 00:55:08
Django
larionov_n, 2015-07-11 00:55:08

Django. How to set an attribute in the main image model (one) from another image attribute (many)?

I tried to make OneToOne with a link to Image, I got a constraint unique error, did migrations, set unique true, verbose_name. Didn't help. Made, thus as separate ImageField. But, I think it's a complete crutch. The second option is to use the main attribute on Image. And then in the model, loop through the images and match it. (Extra code, extra request, crutch, logic in the view, Image Boolean will be in the admin panel). The same if you do the same for Auto (main_image_id: Integer Field and match it, there will be a stupid number in the admin panel). How to do it right?

def get_image_path(instance, filename):
    return os.path.join('photos', str(instance.id), filename)

class Image(models.Model):

    name = models.CharField(max_length=90)
    file = models.ImageField(upload_to=get_image_path, blank=True,  null=True)
    main = models.BooleanField(default=False)

    def __str__(self):
        return "%s" % self.name


class Auto(models.Model):

    name = models.CharField(max_length=40)
    year = models.IntegerField()
    public_date = models.DateField()
    model = models.CharField(max_length=40)
    price = models.IntegerField()
    views = models.IntegerField()
    rating = models.IntegerField()
    description = models.CharField(max_length=200)
    images = models.ManyToManyField(Image)
    main_image = models.ImageField(upload_to=get_image_path, blank=True, null=True)

    def __str__(self):
        return "%s %s" % (self.name, self.model)

    class Meta:
        ordering = ('name', 'price')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2015-07-11
@larionov_n

although most likely you need
https://docs.djangoproject.com/en/1.8/ref/models/f...

images = models.ManyToManyField(Image, related_name="auto_list")
main_image = models.OneToOneField(Image, related_name="auto")

Related_name naming
stackoverflow.com/questions/2642613/what-is-relate...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question