views:

21

answers:

2

if this is my models.py:

class Category(models.Model):
    name = models.CharField(max_length=500)

    slug = models.SlugField(unique=True)

    def __unicode__(self):
        return self.name            

    def get_absolute_url(self):
        return "%s" % self.slug 


class Item(models.Model):
    name = models.CharField(max_length=500)

    slug = models.SlugField(unique=True)

    category = models.ManyToManyField(Category)     

    def __unicode__(self):
        return self.name            

    def get_absolute_url(self):
        return "%s" % self.slug 

My desired functionality is to have any Category that has already had a an Item assigned to it to not be available for any other Items. For example, if I have these Categories: { Animal, Vegetable, Mineral }, and i assign the Item "Rock" to the Category "Mineral", when I add the next Item, "Mineral" will be unavailable from the list in admin. Hopefully that makes sense, and thank you for your time.

A: 

You could specify an "available" field, something like this. And then just show "availables" to the user.

class Category(models.Model):
    name = models.CharField(max_length=500)
    slug = models.SlugField(unique=True)
    available = models.BooleanField(default=True)

    def __unicode__(self):
        return self.name            

    def get_absolute_url(self):
        return "%s" % self.slug 

    def save(self, force_insert=False, force_update=False, using=None):
        if self.item_set.all():
            self.available = False
        super(Category, self).save()
juanefren
Thank you for the answer, but I need it "automated".
tomwolber
A: 

If you only want each Category to be associated with a single Item, then you haven't got a ManyToMany relationship at all. You should restructure your models to make it a ForeignKey from Category to Item.

Daniel Roseman
yes, but each Item can have multiple Categories. It's just not okay for each Category to be used more that once by Items. Hope that makes sense.For example, using the models above, an Item "Horse Sculpture" could be assigned to **both** "Animal" and "Mineral" categories. This would "lock out" those categories, and when adding more Items, "Animal" and "Mineral" would be not be available.
tomwolber
Exactly. The model where an Item can have multiple Categories, but each Category can only be used once, is a many-to-one - implemented in Django as a ForeignKey.
Daniel Roseman