Django Relationship to link two models












2















i am learning django and I am working on an project to make a pizza ordering portal.



I decided to make models for Toppings and Pizza seperately, so that more toppings can be added later and for pizza to of them can be selected, but I cannot seem to figure out the relation schema that should be used to link these two.



I stumbled upon Foreign key method but that is not I want
Here is the part of code for models:



class Topping(models.Model):
name = models.CharField(max_length = 30)

def __str__(self):
return self.name

class Pizza(models.Model):
name = models.CharField(max_length=40)
first_toppping = models.Topping()
second_topping = models.Topping()
# in inches
size = models.IntegerField(max_length=3)
price = models.FloatField()


Please, suggest a method to link these two.










share|improve this question


















  • 1





    Here you should indeed use two ForeignKeys: one for the first_topping, and one for the second_topping. Why do you think that is not applicable.

    – Willem Van Onsem
    Nov 26 '18 at 20:01











  • Foreign key links these two together, but other pizzas should have their toppings too @WillemVanOnsem

    – rohan_aggarwal
    Nov 26 '18 at 20:03











  • well this is exactly what a ForeignKey does: per Pizza, you can link to two toppings. A foreign key is more or less what a reference is in the "object-oriented world".

    – Willem Van Onsem
    Nov 26 '18 at 20:04











  • ok, will try this way. Thanks @WillemVanOnsem

    – rohan_aggarwal
    Nov 26 '18 at 20:06
















2















i am learning django and I am working on an project to make a pizza ordering portal.



I decided to make models for Toppings and Pizza seperately, so that more toppings can be added later and for pizza to of them can be selected, but I cannot seem to figure out the relation schema that should be used to link these two.



I stumbled upon Foreign key method but that is not I want
Here is the part of code for models:



class Topping(models.Model):
name = models.CharField(max_length = 30)

def __str__(self):
return self.name

class Pizza(models.Model):
name = models.CharField(max_length=40)
first_toppping = models.Topping()
second_topping = models.Topping()
# in inches
size = models.IntegerField(max_length=3)
price = models.FloatField()


Please, suggest a method to link these two.










share|improve this question


















  • 1





    Here you should indeed use two ForeignKeys: one for the first_topping, and one for the second_topping. Why do you think that is not applicable.

    – Willem Van Onsem
    Nov 26 '18 at 20:01











  • Foreign key links these two together, but other pizzas should have their toppings too @WillemVanOnsem

    – rohan_aggarwal
    Nov 26 '18 at 20:03











  • well this is exactly what a ForeignKey does: per Pizza, you can link to two toppings. A foreign key is more or less what a reference is in the "object-oriented world".

    – Willem Van Onsem
    Nov 26 '18 at 20:04











  • ok, will try this way. Thanks @WillemVanOnsem

    – rohan_aggarwal
    Nov 26 '18 at 20:06














2












2








2








i am learning django and I am working on an project to make a pizza ordering portal.



I decided to make models for Toppings and Pizza seperately, so that more toppings can be added later and for pizza to of them can be selected, but I cannot seem to figure out the relation schema that should be used to link these two.



I stumbled upon Foreign key method but that is not I want
Here is the part of code for models:



class Topping(models.Model):
name = models.CharField(max_length = 30)

def __str__(self):
return self.name

class Pizza(models.Model):
name = models.CharField(max_length=40)
first_toppping = models.Topping()
second_topping = models.Topping()
# in inches
size = models.IntegerField(max_length=3)
price = models.FloatField()


Please, suggest a method to link these two.










share|improve this question














i am learning django and I am working on an project to make a pizza ordering portal.



I decided to make models for Toppings and Pizza seperately, so that more toppings can be added later and for pizza to of them can be selected, but I cannot seem to figure out the relation schema that should be used to link these two.



I stumbled upon Foreign key method but that is not I want
Here is the part of code for models:



class Topping(models.Model):
name = models.CharField(max_length = 30)

def __str__(self):
return self.name

class Pizza(models.Model):
name = models.CharField(max_length=40)
first_toppping = models.Topping()
second_topping = models.Topping()
# in inches
size = models.IntegerField(max_length=3)
price = models.FloatField()


Please, suggest a method to link these two.







django






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 26 '18 at 19:59









rohan_aggarwalrohan_aggarwal

286




286








  • 1





    Here you should indeed use two ForeignKeys: one for the first_topping, and one for the second_topping. Why do you think that is not applicable.

    – Willem Van Onsem
    Nov 26 '18 at 20:01











  • Foreign key links these two together, but other pizzas should have their toppings too @WillemVanOnsem

    – rohan_aggarwal
    Nov 26 '18 at 20:03











  • well this is exactly what a ForeignKey does: per Pizza, you can link to two toppings. A foreign key is more or less what a reference is in the "object-oriented world".

    – Willem Van Onsem
    Nov 26 '18 at 20:04











  • ok, will try this way. Thanks @WillemVanOnsem

    – rohan_aggarwal
    Nov 26 '18 at 20:06














  • 1





    Here you should indeed use two ForeignKeys: one for the first_topping, and one for the second_topping. Why do you think that is not applicable.

    – Willem Van Onsem
    Nov 26 '18 at 20:01











  • Foreign key links these two together, but other pizzas should have their toppings too @WillemVanOnsem

    – rohan_aggarwal
    Nov 26 '18 at 20:03











  • well this is exactly what a ForeignKey does: per Pizza, you can link to two toppings. A foreign key is more or less what a reference is in the "object-oriented world".

    – Willem Van Onsem
    Nov 26 '18 at 20:04











  • ok, will try this way. Thanks @WillemVanOnsem

    – rohan_aggarwal
    Nov 26 '18 at 20:06








1




1





Here you should indeed use two ForeignKeys: one for the first_topping, and one for the second_topping. Why do you think that is not applicable.

– Willem Van Onsem
Nov 26 '18 at 20:01





Here you should indeed use two ForeignKeys: one for the first_topping, and one for the second_topping. Why do you think that is not applicable.

– Willem Van Onsem
Nov 26 '18 at 20:01













Foreign key links these two together, but other pizzas should have their toppings too @WillemVanOnsem

– rohan_aggarwal
Nov 26 '18 at 20:03





Foreign key links these two together, but other pizzas should have their toppings too @WillemVanOnsem

– rohan_aggarwal
Nov 26 '18 at 20:03













well this is exactly what a ForeignKey does: per Pizza, you can link to two toppings. A foreign key is more or less what a reference is in the "object-oriented world".

– Willem Van Onsem
Nov 26 '18 at 20:04





well this is exactly what a ForeignKey does: per Pizza, you can link to two toppings. A foreign key is more or less what a reference is in the "object-oriented world".

– Willem Van Onsem
Nov 26 '18 at 20:04













ok, will try this way. Thanks @WillemVanOnsem

– rohan_aggarwal
Nov 26 '18 at 20:06





ok, will try this way. Thanks @WillemVanOnsem

– rohan_aggarwal
Nov 26 '18 at 20:06












2 Answers
2






active

oldest

votes


















1














Given that a Pizza has two Toppings, you should add two ForeignKeys to Topping:



from django.utils.translation import gettext_lazy as _

class Topping(models.Model):
# ...
pass

class Pizza(models.Model):
name = models.CharField(max_length=40)
first_toppping = models.ForeignKey(
Topping,
on_delete=models.DO_NOTHING,
related_name='pizza_first'
)
second_topping = models.ForeignKey(
Topping,
on_delete=models.DO_NOTHING,
related_name='pizza_second'
)

size = models.IntegerField(max_length=3)
price = models.FloatField()

def clean(self):
# given we want the two toppings to be different
if self.first_topping_id == self.second_topping_id:
raise ValidationError(_('Toppings should be different.'))
return super(Pizza, self).clean()


or you can make the ForeignKeys nullable, such that if one of the toppings is NULL, this thus means that we do not select a first/second topping:



from django.utils.translation import gettext_lazy as _

class Topping(models.Model):
# ...
pass

class Pizza(models.Model):
name = models.CharField(max_length=40)
first_toppping = models.ForeignKey(
Topping,
on_delete=models.SET_NULL,
null=True,
related_name='pizza_first'
)
second_topping = models.ForeignKey(
Topping,
on_delete=models.SET_NULL,
null=True,
related_name='pizza_second'
)

size = models.IntegerField(max_length=3)
price = models.FloatField()

def clean(self):
# given we want the two toppings to be different
if self.first_topping_id is not None and self.second_topping_id is not None and self.first_topping_id == self.second_topping_id:
raise ValidationError(_('Toppings should be different.'))
return super(Pizza, self).clean()


Here we thus model that a pizza links twice to a topping.



Depending on the the application, you might want to allow a user to pick an arbitrary number of toppings, and sometimes it is even possible to pick the same topping multiple times.



We can use a ManyToManyField [Django-doc] for that, and in case we want to be able to add the same topping twice (or more) we can work with a through table, like:



# a pizza can have the same topping multiple times

class Topping(models.Model):
# ...
pass

class PizzaTopping(models.Model):
pizza = models.ForeignKey('Pizza')
topping = models.ForeignKey(Topping)

class Pizza(models.Model):
name = models.CharField(max_length=40)
toppping = models.ManyToManyField(
Topping,
through=PizzaTopping,
related_name='pizzas'
)

size = models.IntegerField(max_length=3)
price = models.FloatField()





share|improve this answer


























  • thanks for the help, is there a way to enforce both toppings as unique for a pizza in Foreign key method

    – rohan_aggarwal
    Nov 26 '18 at 21:04











  • @rohan_aggarwal: unique in what sense: that a pizza should have two different toppings, or that each topping can only be used for, at most, one pizza?

    – Willem Van Onsem
    Nov 26 '18 at 21:09











  • A pizza should have two different toppings

    – rohan_aggarwal
    Nov 26 '18 at 21:11











  • @rohan_aggarwal: you can enforce this at the Django level (not at the database level, or not without some extra packages) by patching the clean() method, as demonstrated in the first code fragment.

    – Willem Van Onsem
    Nov 26 '18 at 21:16











  • or I an enforce this in form too

    – rohan_aggarwal
    Nov 26 '18 at 21:27



















2














If I understand you correcyly, each pizza has many toppings, so you have to use many to many. This way, you can add as many toppings as you want (0-*)



class Topping(models.Model):
name = models.CharField(max_length = 30, unique = True)

def __str__(self):
return self.name

class Pizza(models.Model):
name = models.CharField(max_length=40)
toppings = models.ManyToManyField(Topping)
# in inches
size = models.IntegerField(max_length=3)
price = models.FloatField()


As you can see in the following example, I create a pizza object and I add as many toppings as I want :



pizza = Pizza(name="CheesePizza",size=5,price=25.22)
pizza.save()

topping1 = Topping(name="chocolate")
topping1.save()
topping2 = Topping(name="whataver")
topping2.save()
topping3 = Topping(name="component")
topping3.save()

pizza.toppings.add(topping1,topping2,topping3)





share|improve this answer





















  • 1





    And what if I want to make it 2, like two toppings are must for a pizza will this relationship still hold, or I need extra functioanlity to enforce this rule

    – rohan_aggarwal
    Nov 26 '18 at 20:17








  • 1





    There can however be a problem here if one can order the same topping twice (some restaurants do this such that "two" equal toppings means the much of that topping). This can however be solved with a through table.

    – Willem Van Onsem
    Nov 26 '18 at 20:25






  • 1





    can you suggest method to make name unique

    – rohan_aggarwal
    Nov 26 '18 at 20:29






  • 1





    @AmineMessaoudi: exactly.

    – Willem Van Onsem
    Nov 26 '18 at 20:35






  • 1





    @AmineMessaoudi: no, what I mean is that here you can only add topping1 once, if you call this twice, the second time it will have no effect. But in some restaurants, you want to add it a second time.

    – Willem Van Onsem
    Nov 26 '18 at 20:39











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53488155%2fdjango-relationship-to-link-two-models%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














Given that a Pizza has two Toppings, you should add two ForeignKeys to Topping:



from django.utils.translation import gettext_lazy as _

class Topping(models.Model):
# ...
pass

class Pizza(models.Model):
name = models.CharField(max_length=40)
first_toppping = models.ForeignKey(
Topping,
on_delete=models.DO_NOTHING,
related_name='pizza_first'
)
second_topping = models.ForeignKey(
Topping,
on_delete=models.DO_NOTHING,
related_name='pizza_second'
)

size = models.IntegerField(max_length=3)
price = models.FloatField()

def clean(self):
# given we want the two toppings to be different
if self.first_topping_id == self.second_topping_id:
raise ValidationError(_('Toppings should be different.'))
return super(Pizza, self).clean()


or you can make the ForeignKeys nullable, such that if one of the toppings is NULL, this thus means that we do not select a first/second topping:



from django.utils.translation import gettext_lazy as _

class Topping(models.Model):
# ...
pass

class Pizza(models.Model):
name = models.CharField(max_length=40)
first_toppping = models.ForeignKey(
Topping,
on_delete=models.SET_NULL,
null=True,
related_name='pizza_first'
)
second_topping = models.ForeignKey(
Topping,
on_delete=models.SET_NULL,
null=True,
related_name='pizza_second'
)

size = models.IntegerField(max_length=3)
price = models.FloatField()

def clean(self):
# given we want the two toppings to be different
if self.first_topping_id is not None and self.second_topping_id is not None and self.first_topping_id == self.second_topping_id:
raise ValidationError(_('Toppings should be different.'))
return super(Pizza, self).clean()


Here we thus model that a pizza links twice to a topping.



Depending on the the application, you might want to allow a user to pick an arbitrary number of toppings, and sometimes it is even possible to pick the same topping multiple times.



We can use a ManyToManyField [Django-doc] for that, and in case we want to be able to add the same topping twice (or more) we can work with a through table, like:



# a pizza can have the same topping multiple times

class Topping(models.Model):
# ...
pass

class PizzaTopping(models.Model):
pizza = models.ForeignKey('Pizza')
topping = models.ForeignKey(Topping)

class Pizza(models.Model):
name = models.CharField(max_length=40)
toppping = models.ManyToManyField(
Topping,
through=PizzaTopping,
related_name='pizzas'
)

size = models.IntegerField(max_length=3)
price = models.FloatField()





share|improve this answer


























  • thanks for the help, is there a way to enforce both toppings as unique for a pizza in Foreign key method

    – rohan_aggarwal
    Nov 26 '18 at 21:04











  • @rohan_aggarwal: unique in what sense: that a pizza should have two different toppings, or that each topping can only be used for, at most, one pizza?

    – Willem Van Onsem
    Nov 26 '18 at 21:09











  • A pizza should have two different toppings

    – rohan_aggarwal
    Nov 26 '18 at 21:11











  • @rohan_aggarwal: you can enforce this at the Django level (not at the database level, or not without some extra packages) by patching the clean() method, as demonstrated in the first code fragment.

    – Willem Van Onsem
    Nov 26 '18 at 21:16











  • or I an enforce this in form too

    – rohan_aggarwal
    Nov 26 '18 at 21:27
















1














Given that a Pizza has two Toppings, you should add two ForeignKeys to Topping:



from django.utils.translation import gettext_lazy as _

class Topping(models.Model):
# ...
pass

class Pizza(models.Model):
name = models.CharField(max_length=40)
first_toppping = models.ForeignKey(
Topping,
on_delete=models.DO_NOTHING,
related_name='pizza_first'
)
second_topping = models.ForeignKey(
Topping,
on_delete=models.DO_NOTHING,
related_name='pizza_second'
)

size = models.IntegerField(max_length=3)
price = models.FloatField()

def clean(self):
# given we want the two toppings to be different
if self.first_topping_id == self.second_topping_id:
raise ValidationError(_('Toppings should be different.'))
return super(Pizza, self).clean()


or you can make the ForeignKeys nullable, such that if one of the toppings is NULL, this thus means that we do not select a first/second topping:



from django.utils.translation import gettext_lazy as _

class Topping(models.Model):
# ...
pass

class Pizza(models.Model):
name = models.CharField(max_length=40)
first_toppping = models.ForeignKey(
Topping,
on_delete=models.SET_NULL,
null=True,
related_name='pizza_first'
)
second_topping = models.ForeignKey(
Topping,
on_delete=models.SET_NULL,
null=True,
related_name='pizza_second'
)

size = models.IntegerField(max_length=3)
price = models.FloatField()

def clean(self):
# given we want the two toppings to be different
if self.first_topping_id is not None and self.second_topping_id is not None and self.first_topping_id == self.second_topping_id:
raise ValidationError(_('Toppings should be different.'))
return super(Pizza, self).clean()


Here we thus model that a pizza links twice to a topping.



Depending on the the application, you might want to allow a user to pick an arbitrary number of toppings, and sometimes it is even possible to pick the same topping multiple times.



We can use a ManyToManyField [Django-doc] for that, and in case we want to be able to add the same topping twice (or more) we can work with a through table, like:



# a pizza can have the same topping multiple times

class Topping(models.Model):
# ...
pass

class PizzaTopping(models.Model):
pizza = models.ForeignKey('Pizza')
topping = models.ForeignKey(Topping)

class Pizza(models.Model):
name = models.CharField(max_length=40)
toppping = models.ManyToManyField(
Topping,
through=PizzaTopping,
related_name='pizzas'
)

size = models.IntegerField(max_length=3)
price = models.FloatField()





share|improve this answer


























  • thanks for the help, is there a way to enforce both toppings as unique for a pizza in Foreign key method

    – rohan_aggarwal
    Nov 26 '18 at 21:04











  • @rohan_aggarwal: unique in what sense: that a pizza should have two different toppings, or that each topping can only be used for, at most, one pizza?

    – Willem Van Onsem
    Nov 26 '18 at 21:09











  • A pizza should have two different toppings

    – rohan_aggarwal
    Nov 26 '18 at 21:11











  • @rohan_aggarwal: you can enforce this at the Django level (not at the database level, or not without some extra packages) by patching the clean() method, as demonstrated in the first code fragment.

    – Willem Van Onsem
    Nov 26 '18 at 21:16











  • or I an enforce this in form too

    – rohan_aggarwal
    Nov 26 '18 at 21:27














1












1








1







Given that a Pizza has two Toppings, you should add two ForeignKeys to Topping:



from django.utils.translation import gettext_lazy as _

class Topping(models.Model):
# ...
pass

class Pizza(models.Model):
name = models.CharField(max_length=40)
first_toppping = models.ForeignKey(
Topping,
on_delete=models.DO_NOTHING,
related_name='pizza_first'
)
second_topping = models.ForeignKey(
Topping,
on_delete=models.DO_NOTHING,
related_name='pizza_second'
)

size = models.IntegerField(max_length=3)
price = models.FloatField()

def clean(self):
# given we want the two toppings to be different
if self.first_topping_id == self.second_topping_id:
raise ValidationError(_('Toppings should be different.'))
return super(Pizza, self).clean()


or you can make the ForeignKeys nullable, such that if one of the toppings is NULL, this thus means that we do not select a first/second topping:



from django.utils.translation import gettext_lazy as _

class Topping(models.Model):
# ...
pass

class Pizza(models.Model):
name = models.CharField(max_length=40)
first_toppping = models.ForeignKey(
Topping,
on_delete=models.SET_NULL,
null=True,
related_name='pizza_first'
)
second_topping = models.ForeignKey(
Topping,
on_delete=models.SET_NULL,
null=True,
related_name='pizza_second'
)

size = models.IntegerField(max_length=3)
price = models.FloatField()

def clean(self):
# given we want the two toppings to be different
if self.first_topping_id is not None and self.second_topping_id is not None and self.first_topping_id == self.second_topping_id:
raise ValidationError(_('Toppings should be different.'))
return super(Pizza, self).clean()


Here we thus model that a pizza links twice to a topping.



Depending on the the application, you might want to allow a user to pick an arbitrary number of toppings, and sometimes it is even possible to pick the same topping multiple times.



We can use a ManyToManyField [Django-doc] for that, and in case we want to be able to add the same topping twice (or more) we can work with a through table, like:



# a pizza can have the same topping multiple times

class Topping(models.Model):
# ...
pass

class PizzaTopping(models.Model):
pizza = models.ForeignKey('Pizza')
topping = models.ForeignKey(Topping)

class Pizza(models.Model):
name = models.CharField(max_length=40)
toppping = models.ManyToManyField(
Topping,
through=PizzaTopping,
related_name='pizzas'
)

size = models.IntegerField(max_length=3)
price = models.FloatField()





share|improve this answer















Given that a Pizza has two Toppings, you should add two ForeignKeys to Topping:



from django.utils.translation import gettext_lazy as _

class Topping(models.Model):
# ...
pass

class Pizza(models.Model):
name = models.CharField(max_length=40)
first_toppping = models.ForeignKey(
Topping,
on_delete=models.DO_NOTHING,
related_name='pizza_first'
)
second_topping = models.ForeignKey(
Topping,
on_delete=models.DO_NOTHING,
related_name='pizza_second'
)

size = models.IntegerField(max_length=3)
price = models.FloatField()

def clean(self):
# given we want the two toppings to be different
if self.first_topping_id == self.second_topping_id:
raise ValidationError(_('Toppings should be different.'))
return super(Pizza, self).clean()


or you can make the ForeignKeys nullable, such that if one of the toppings is NULL, this thus means that we do not select a first/second topping:



from django.utils.translation import gettext_lazy as _

class Topping(models.Model):
# ...
pass

class Pizza(models.Model):
name = models.CharField(max_length=40)
first_toppping = models.ForeignKey(
Topping,
on_delete=models.SET_NULL,
null=True,
related_name='pizza_first'
)
second_topping = models.ForeignKey(
Topping,
on_delete=models.SET_NULL,
null=True,
related_name='pizza_second'
)

size = models.IntegerField(max_length=3)
price = models.FloatField()

def clean(self):
# given we want the two toppings to be different
if self.first_topping_id is not None and self.second_topping_id is not None and self.first_topping_id == self.second_topping_id:
raise ValidationError(_('Toppings should be different.'))
return super(Pizza, self).clean()


Here we thus model that a pizza links twice to a topping.



Depending on the the application, you might want to allow a user to pick an arbitrary number of toppings, and sometimes it is even possible to pick the same topping multiple times.



We can use a ManyToManyField [Django-doc] for that, and in case we want to be able to add the same topping twice (or more) we can work with a through table, like:



# a pizza can have the same topping multiple times

class Topping(models.Model):
# ...
pass

class PizzaTopping(models.Model):
pizza = models.ForeignKey('Pizza')
topping = models.ForeignKey(Topping)

class Pizza(models.Model):
name = models.CharField(max_length=40)
toppping = models.ManyToManyField(
Topping,
through=PizzaTopping,
related_name='pizzas'
)

size = models.IntegerField(max_length=3)
price = models.FloatField()






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 26 '18 at 21:15

























answered Nov 26 '18 at 20:43









Willem Van OnsemWillem Van Onsem

148k16143233




148k16143233













  • thanks for the help, is there a way to enforce both toppings as unique for a pizza in Foreign key method

    – rohan_aggarwal
    Nov 26 '18 at 21:04











  • @rohan_aggarwal: unique in what sense: that a pizza should have two different toppings, or that each topping can only be used for, at most, one pizza?

    – Willem Van Onsem
    Nov 26 '18 at 21:09











  • A pizza should have two different toppings

    – rohan_aggarwal
    Nov 26 '18 at 21:11











  • @rohan_aggarwal: you can enforce this at the Django level (not at the database level, or not without some extra packages) by patching the clean() method, as demonstrated in the first code fragment.

    – Willem Van Onsem
    Nov 26 '18 at 21:16











  • or I an enforce this in form too

    – rohan_aggarwal
    Nov 26 '18 at 21:27



















  • thanks for the help, is there a way to enforce both toppings as unique for a pizza in Foreign key method

    – rohan_aggarwal
    Nov 26 '18 at 21:04











  • @rohan_aggarwal: unique in what sense: that a pizza should have two different toppings, or that each topping can only be used for, at most, one pizza?

    – Willem Van Onsem
    Nov 26 '18 at 21:09











  • A pizza should have two different toppings

    – rohan_aggarwal
    Nov 26 '18 at 21:11











  • @rohan_aggarwal: you can enforce this at the Django level (not at the database level, or not without some extra packages) by patching the clean() method, as demonstrated in the first code fragment.

    – Willem Van Onsem
    Nov 26 '18 at 21:16











  • or I an enforce this in form too

    – rohan_aggarwal
    Nov 26 '18 at 21:27

















thanks for the help, is there a way to enforce both toppings as unique for a pizza in Foreign key method

– rohan_aggarwal
Nov 26 '18 at 21:04





thanks for the help, is there a way to enforce both toppings as unique for a pizza in Foreign key method

– rohan_aggarwal
Nov 26 '18 at 21:04













@rohan_aggarwal: unique in what sense: that a pizza should have two different toppings, or that each topping can only be used for, at most, one pizza?

– Willem Van Onsem
Nov 26 '18 at 21:09





@rohan_aggarwal: unique in what sense: that a pizza should have two different toppings, or that each topping can only be used for, at most, one pizza?

– Willem Van Onsem
Nov 26 '18 at 21:09













A pizza should have two different toppings

– rohan_aggarwal
Nov 26 '18 at 21:11





A pizza should have two different toppings

– rohan_aggarwal
Nov 26 '18 at 21:11













@rohan_aggarwal: you can enforce this at the Django level (not at the database level, or not without some extra packages) by patching the clean() method, as demonstrated in the first code fragment.

– Willem Van Onsem
Nov 26 '18 at 21:16





@rohan_aggarwal: you can enforce this at the Django level (not at the database level, or not without some extra packages) by patching the clean() method, as demonstrated in the first code fragment.

– Willem Van Onsem
Nov 26 '18 at 21:16













or I an enforce this in form too

– rohan_aggarwal
Nov 26 '18 at 21:27





or I an enforce this in form too

– rohan_aggarwal
Nov 26 '18 at 21:27













2














If I understand you correcyly, each pizza has many toppings, so you have to use many to many. This way, you can add as many toppings as you want (0-*)



class Topping(models.Model):
name = models.CharField(max_length = 30, unique = True)

def __str__(self):
return self.name

class Pizza(models.Model):
name = models.CharField(max_length=40)
toppings = models.ManyToManyField(Topping)
# in inches
size = models.IntegerField(max_length=3)
price = models.FloatField()


As you can see in the following example, I create a pizza object and I add as many toppings as I want :



pizza = Pizza(name="CheesePizza",size=5,price=25.22)
pizza.save()

topping1 = Topping(name="chocolate")
topping1.save()
topping2 = Topping(name="whataver")
topping2.save()
topping3 = Topping(name="component")
topping3.save()

pizza.toppings.add(topping1,topping2,topping3)





share|improve this answer





















  • 1





    And what if I want to make it 2, like two toppings are must for a pizza will this relationship still hold, or I need extra functioanlity to enforce this rule

    – rohan_aggarwal
    Nov 26 '18 at 20:17








  • 1





    There can however be a problem here if one can order the same topping twice (some restaurants do this such that "two" equal toppings means the much of that topping). This can however be solved with a through table.

    – Willem Van Onsem
    Nov 26 '18 at 20:25






  • 1





    can you suggest method to make name unique

    – rohan_aggarwal
    Nov 26 '18 at 20:29






  • 1





    @AmineMessaoudi: exactly.

    – Willem Van Onsem
    Nov 26 '18 at 20:35






  • 1





    @AmineMessaoudi: no, what I mean is that here you can only add topping1 once, if you call this twice, the second time it will have no effect. But in some restaurants, you want to add it a second time.

    – Willem Van Onsem
    Nov 26 '18 at 20:39
















2














If I understand you correcyly, each pizza has many toppings, so you have to use many to many. This way, you can add as many toppings as you want (0-*)



class Topping(models.Model):
name = models.CharField(max_length = 30, unique = True)

def __str__(self):
return self.name

class Pizza(models.Model):
name = models.CharField(max_length=40)
toppings = models.ManyToManyField(Topping)
# in inches
size = models.IntegerField(max_length=3)
price = models.FloatField()


As you can see in the following example, I create a pizza object and I add as many toppings as I want :



pizza = Pizza(name="CheesePizza",size=5,price=25.22)
pizza.save()

topping1 = Topping(name="chocolate")
topping1.save()
topping2 = Topping(name="whataver")
topping2.save()
topping3 = Topping(name="component")
topping3.save()

pizza.toppings.add(topping1,topping2,topping3)





share|improve this answer





















  • 1





    And what if I want to make it 2, like two toppings are must for a pizza will this relationship still hold, or I need extra functioanlity to enforce this rule

    – rohan_aggarwal
    Nov 26 '18 at 20:17








  • 1





    There can however be a problem here if one can order the same topping twice (some restaurants do this such that "two" equal toppings means the much of that topping). This can however be solved with a through table.

    – Willem Van Onsem
    Nov 26 '18 at 20:25






  • 1





    can you suggest method to make name unique

    – rohan_aggarwal
    Nov 26 '18 at 20:29






  • 1





    @AmineMessaoudi: exactly.

    – Willem Van Onsem
    Nov 26 '18 at 20:35






  • 1





    @AmineMessaoudi: no, what I mean is that here you can only add topping1 once, if you call this twice, the second time it will have no effect. But in some restaurants, you want to add it a second time.

    – Willem Van Onsem
    Nov 26 '18 at 20:39














2












2








2







If I understand you correcyly, each pizza has many toppings, so you have to use many to many. This way, you can add as many toppings as you want (0-*)



class Topping(models.Model):
name = models.CharField(max_length = 30, unique = True)

def __str__(self):
return self.name

class Pizza(models.Model):
name = models.CharField(max_length=40)
toppings = models.ManyToManyField(Topping)
# in inches
size = models.IntegerField(max_length=3)
price = models.FloatField()


As you can see in the following example, I create a pizza object and I add as many toppings as I want :



pizza = Pizza(name="CheesePizza",size=5,price=25.22)
pizza.save()

topping1 = Topping(name="chocolate")
topping1.save()
topping2 = Topping(name="whataver")
topping2.save()
topping3 = Topping(name="component")
topping3.save()

pizza.toppings.add(topping1,topping2,topping3)





share|improve this answer















If I understand you correcyly, each pizza has many toppings, so you have to use many to many. This way, you can add as many toppings as you want (0-*)



class Topping(models.Model):
name = models.CharField(max_length = 30, unique = True)

def __str__(self):
return self.name

class Pizza(models.Model):
name = models.CharField(max_length=40)
toppings = models.ManyToManyField(Topping)
# in inches
size = models.IntegerField(max_length=3)
price = models.FloatField()


As you can see in the following example, I create a pizza object and I add as many toppings as I want :



pizza = Pizza(name="CheesePizza",size=5,price=25.22)
pizza.save()

topping1 = Topping(name="chocolate")
topping1.save()
topping2 = Topping(name="whataver")
topping2.save()
topping3 = Topping(name="component")
topping3.save()

pizza.toppings.add(topping1,topping2,topping3)






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 26 '18 at 20:28

























answered Nov 26 '18 at 20:08









Amine MessaoudiAmine Messaoudi

526514




526514








  • 1





    And what if I want to make it 2, like two toppings are must for a pizza will this relationship still hold, or I need extra functioanlity to enforce this rule

    – rohan_aggarwal
    Nov 26 '18 at 20:17








  • 1





    There can however be a problem here if one can order the same topping twice (some restaurants do this such that "two" equal toppings means the much of that topping). This can however be solved with a through table.

    – Willem Van Onsem
    Nov 26 '18 at 20:25






  • 1





    can you suggest method to make name unique

    – rohan_aggarwal
    Nov 26 '18 at 20:29






  • 1





    @AmineMessaoudi: exactly.

    – Willem Van Onsem
    Nov 26 '18 at 20:35






  • 1





    @AmineMessaoudi: no, what I mean is that here you can only add topping1 once, if you call this twice, the second time it will have no effect. But in some restaurants, you want to add it a second time.

    – Willem Van Onsem
    Nov 26 '18 at 20:39














  • 1





    And what if I want to make it 2, like two toppings are must for a pizza will this relationship still hold, or I need extra functioanlity to enforce this rule

    – rohan_aggarwal
    Nov 26 '18 at 20:17








  • 1





    There can however be a problem here if one can order the same topping twice (some restaurants do this such that "two" equal toppings means the much of that topping). This can however be solved with a through table.

    – Willem Van Onsem
    Nov 26 '18 at 20:25






  • 1





    can you suggest method to make name unique

    – rohan_aggarwal
    Nov 26 '18 at 20:29






  • 1





    @AmineMessaoudi: exactly.

    – Willem Van Onsem
    Nov 26 '18 at 20:35






  • 1





    @AmineMessaoudi: no, what I mean is that here you can only add topping1 once, if you call this twice, the second time it will have no effect. But in some restaurants, you want to add it a second time.

    – Willem Van Onsem
    Nov 26 '18 at 20:39








1




1





And what if I want to make it 2, like two toppings are must for a pizza will this relationship still hold, or I need extra functioanlity to enforce this rule

– rohan_aggarwal
Nov 26 '18 at 20:17







And what if I want to make it 2, like two toppings are must for a pizza will this relationship still hold, or I need extra functioanlity to enforce this rule

– rohan_aggarwal
Nov 26 '18 at 20:17






1




1





There can however be a problem here if one can order the same topping twice (some restaurants do this such that "two" equal toppings means the much of that topping). This can however be solved with a through table.

– Willem Van Onsem
Nov 26 '18 at 20:25





There can however be a problem here if one can order the same topping twice (some restaurants do this such that "two" equal toppings means the much of that topping). This can however be solved with a through table.

– Willem Van Onsem
Nov 26 '18 at 20:25




1




1





can you suggest method to make name unique

– rohan_aggarwal
Nov 26 '18 at 20:29





can you suggest method to make name unique

– rohan_aggarwal
Nov 26 '18 at 20:29




1




1





@AmineMessaoudi: exactly.

– Willem Van Onsem
Nov 26 '18 at 20:35





@AmineMessaoudi: exactly.

– Willem Van Onsem
Nov 26 '18 at 20:35




1




1





@AmineMessaoudi: no, what I mean is that here you can only add topping1 once, if you call this twice, the second time it will have no effect. But in some restaurants, you want to add it a second time.

– Willem Van Onsem
Nov 26 '18 at 20:39





@AmineMessaoudi: no, what I mean is that here you can only add topping1 once, if you call this twice, the second time it will have no effect. But in some restaurants, you want to add it a second time.

– Willem Van Onsem
Nov 26 '18 at 20:39


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53488155%2fdjango-relationship-to-link-two-models%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

Calculate evaluation metrics using cross_val_predict sklearn

Insert data from modal to MySQL (multiple modal on website)