Jack
Jack

Reputation: 55

Django models, set unqiue attribute for M2M field per object

Currently, have a database with an Item table and a Stock table. There is a many to many relationship between the two. A single item object can have many sizes. The next step is to assign an 'inStock' options to the item per size. Any thoughts on acheiving this?

Current models.py

class Stock(models.Model):
    size = models.CharField(max_length=30)
    stock = models.BooleanField(default=False)
    def __str__(self):
        return self.size

class Item(models.Model):
    title = models.CharField(max_length=250, null=True, unique=True)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    aw_product_id = models.CharField(max_length=11, null=True) # Removed because multiple products has similar identifer
    url = models.URLField(max_length=250)           # Removed 'unique=True'as the aw_prod_id will throw an integrity error
    image = models.CharField(max_length=1000)
    retailer = models.CharField(max_length=250)
    category = models.CharField(max_length=100)
    featured = models.CharField(max_length=10, default='NO')
    gender = models.CharField(max_length=100, null=True)
    sizes = models.ManyToManyField(Stock)
    uniq_id = models.CharField(max_length=11, null=True, unique=True) # Removed because multiple products has similar identifer

    def __str__(self):
        return self.title

Upvotes: 0

Views: 116

Answers (1)

Vinay Pai
Vinay Pai

Reputation: 7758

You can use the through argument to ManyToManyField to specify another model to use for the relationship, with additional fields instead of the autogenerated model that django creates by default.

Upvotes: 1

Related Questions