On Sun, 16 Nov 2014 23:51:16 -0800 (PST)
ThomasTheDjangoFan <stefan.eichholz.ber...@googlemail.com> wrote:

> Hi guys,
> 
> I'd like to only be able to assign many ProcutImages to a Product, but only 
> ONE Image as a default image per product 
> (ProductImage.is_default_image=True).
> 
> I can't get this to work correnctly on Django 1.7 with a db.sqlite3: With 
> the code below I can only assign ONE Image to a Product. After that I get 
> the error "Product image with this Product und Is default image already 
> exists.".
> 
> Am I getting something wrong?
> 
> from django.db import models
> 
> class Product(models.Model):
>     title = models.CharField(max_length=255)
>     
>     is_active = models.BooleanField(default=True)
> 
> 
> class ProductImage(models.Model):
>     product = models.ForeignKey(Product)
> 
>     image = models.ImageField(upload_to='products/images/')
> 
>     is_default_image = models.BooleanField(default=False,null=False,blank=
> False)
> 
>     class Meta:
>         # A product can have multiple ProductImages, but only one of them 
> can be the "default"-image
>         unique_together = ('product', 'is_default_image')
> 
> I would be really thankful for some tips.

Well boolean field can have only two values: "true" or "false".

Now your unique_together defines that for "product" combined with 
"is_default_image" must be unique. Which means that for each product you can 
have _two_ images, one where is_default_image is true and one where 
is_default_image is false. And this is forced on database level as well.

But apparently that is what you intended to do. There isn't really one single 
solution for your problem.

-- 

Jani Tiainen

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/20141117122459.5de8b80b%40jns42-l.w2k.keypro.fi.
For more options, visit https://groups.google.com/d/optout.

Reply via email to