A.Raouf
A.Raouf

Reputation: 2320

ForeignKey(unique=True) is usually better served by a OneToOneField

class Categories(models.Model):
    id = models.ForeignKey('auth.User',primary_key=True)
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=300)

    def __str__(self):
        return Categories.name

    class Meta:
        order_with_respect_to = 'id'


class Specializations(models.Model):
    id = models.ForeignKey('auth.User',primary_key=True)
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=300)
    categories = models.ForeignKey(Categories, on_delete=models.CASCADE)


    def __str__(self):
        return Specializations.name

courses.Categories.id: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneTo OneField.

    HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.

courses.Courses.id: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOne Field.

    HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.

courses.Specializations.id: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.

This warning or error raises although the relation is one to many !! not one to one

Upvotes: 2

Views: 7084

Answers (1)

ilse2005
ilse2005

Reputation: 11429

The way you designed your models it is essentially a OneToOne relationship, because you set the ForeignKey to be the primary_key (this automatically aplies unique=True).

Do you really want to the user to be the primary_key of Categories or Specializations?

I think you want something like this:

class Categories(models.Model):
    user = models.ForeignKey('auth.User')
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=300)

    def __str__(self):
        return self.name


class Specializations(models.Model):
    user = models.ForeignKey('auth.User')
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=300)
    categories = models.ForeignKey(Categories, on_delete=models.CASCADE)


    def __str__(self):
        return self.name

With this a User can have many Categories and Specializations I also changed the __str__ method to self.name

Upvotes: 6

Related Questions