The intermediary model has no field

Viewed 69

i'm newbie in Django world i'm creating a web app to manage products in an online store i created the models for Catergories and Products here are my models :

from django.db import models

# Create your models here.


class Category(models.Model):
    name = models.CharField(max_length=255, unique=True, )
    description = models.TextField(max_length=1500)


    def __str__(self):
        return self.name


class Product(models.Model):

    name = models.CharField(max_length=255)
    description = models.TextField()
    nominal_price = models.PositiveIntegerField(verbose_name='prix normal',)
    reduced_price = models.PositiveIntegerField(blank=True, null=True)
    categories = models.ManyToManyField('Category', through='CategoryProducts', through_fields=('category','product'))

    def __str__(self):
        return self.name


class CategoryProducts(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE, )
    product = models.ForeignKey(Product, on_delete=models.CASCADE, )
1 Answers

The through_fields=… [Django-doc] are ordered such that the first item is a field that refers to the source model: the model where you define the ManyToManyField, and the second is the target model: the model where the ManyToManyField is referring to, so you define these as:

class Product(models.Model):
    # …
    categories = models.ManyToManyField(
        'Category',
        through='CategoryProducts',
        through_fields=('product', 'category')
    )
Related