Как поместить цену продукта с помощью поля ManyToManyField между таблицей Sellers и таблицей Products

Мне нужна цена продукта между двумя таблицами Sellers и Products.

Вот мои модели -

class Products(models.Model):
    name = models.CharField(max_length=60)
    price= models.IntegerField(default=0)
    category= models.ForeignKey(Category,on_delete=models.CASCADE,default=1 )
    description= models.TextField(blank=True, null= True)
    image= models.ImageField(upload_to='uploads/products/')

    def __str__(self):
        return self.name



class Sellers(models.Model):
    name = models.CharField(max_length=60)
    products = models.ManyToManyField(Products)
    description= models.TextField(blank=True, null= True)
    image= models.ImageField(upload_to='uploads/sellers/')

    def __str__(self):
        return self.name

Где разместить цену товара для каждого продавца?

Я бы создал новый класс Price и хранил в нем цены продавца:

class Price(models.Model):
     seller = models.ForeignKey(Seller,on_delete=models.CASCADE)
     product = models.ForeignKey(Product,on_delete=models.CASCADE)
     price = models.IntegerField()

Вам следует рассмотреть возможность создания ограничения уникальности, чтобы избежать множественной цены продукта для одной комбинации продавца продукта

You can define this in the junction table [wiki] of the ManyToManyField by specifying a through=… model [Django-doc]:

class Product(models.Model):
    name = models.CharField(max_length=60)
    price = models.IntegerField(default=0)
    category = models.ForeignKey(Category,on_delete=models.CASCADE,default=1 )
    description = models.TextField(blank=True, null= True)
    image = models.ImageField(upload_to='uploads/products/')

    def __str__(self):
        return self.name


class Seller(models.Model):
    name = models.CharField(max_length=60)
    products = models.ManyToManyField(
        Product,
        through='SellerProduct'
    )
    description= models.TextField(blank=True, null= True)
    image= models.ImageField(upload_to='uploads/sellers/')

    def __str__(self):
        return self.name

class SellerProduct(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    seller = models.ForeignKey(Seller, on_delete=models.CASCADE)
    price = models.IntegerField()
Вернуться на верх