Reputation: 791
how to choice multiple instances of a foreignkey for example
class Mobile(models.Model):
mobile = models.CharField(max_length=20,unique=True)
quantity = models.IntegerField()
imei = models.ForeignKey(Imei,on_delete=models.CASCADE)
class Imei(models.Model):
imei = models.CharField(max_length=13,unique=True)
each mobile have different Imei
in Mobile
if mobile =samsung A51
and quantity = 10
then we have 10 unique imei
i want to know how to let the user the select 10 imei's (with barcode reader) in the same form ?
i appreciate your helps
Upvotes: 0
Views: 58
Reputation: 1107
I think what you need here is ManyToMany relation. Your Mobile
model will look like.
class Mobile(models.Model):
mobile = models.CharField()
quantity = models.IntegerField(
imei = models.ManyToManyField(Imei)
EDITED: Since there are unique imei for each Mobile
, you have 2 options to achieve this
ManyToManyField
. (I think this will simplify your relationships)Mobile
table and Imei
table. Create another table to store the relationship of both, let's say MobielImei
with following fieldsclass MobileImei(models.Model):
mobile = models.ForeignKey(Mobile)
imei = models.ForeignKey(Imei)
class Meta:
unique_together = ("mobile", "imei")
This unique_together
will ensure, that for every mobile there's a unique imei
and single imei
is also associated to a unique mobile.
Upvotes: 1