0

Suppose I have a model structure like this:

class Cheese(Model.models):
    type = models.CharField(max_length='50')

class Sauce(Models.models):
    type = models.CharField(max_length='50')

class Pizza(Models.models):
    cheese = models.ForeignKey(Cheese)
    sauce = models.ForeignKey(Sauce)

class PizzaOrder(Models.model):
    pizza = models.ForeignKey(Pizza)
    time = models.DateTimeField(auto_now_add=True)

Given this, now I want to create a new entry for PizzaOrder--but I do not want any duplicates of Cheese, Sauce, or Pizza--just PizzaOrder to represent that a pizza was just ordered.

This results in an error, which is discussed here.

How can I avoid this problem? I do not want a duplicate of object Pizza every-time I get a new PizzaOrder.

user8951490
  • 833
  • 1
  • 10
  • 21

1 Answers1

0

If you want to avoid creating duplicate Cheese, Sauce and Pizza, you can do like this:

class Cheese(Model.models):
    type = models.CharField(max_length='50', unique=True)

class Sauce(Models.models):
    type = models.CharField(max_length='50', unique=True)

class Pizza(Models.models):
    cheese = models.ForeignKey(Cheese)
    sauce = models.ForeignKey(Sauce)

    class Meta:
         unique_togather=(("cheese", "sauce"),)
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • I used the unique attribute and it broke my database... Getting an error `django.db.utils.IntegrityError: UNIQUE constraint failed:` I thought removing the unique attributes would fix it, but it did not, so I put them back in and made sure their values were all "False"... Still the error is there, I am guessing there is some kind of cachcing mechanism. – user8951490 Nov 23 '17 at 09:39
  • Maybe you were trying to save duplicate value in DB, or tables contain duplicate values(if its that case, try removing duplicate values from DB). – ruddra Nov 23 '17 at 10:06