art_cs
art_cs

Reputation: 791

foreignkey django

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

Answers (1)

Sadan A.
Sadan A.

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

  1. Either implement the unique validation at the time of adding an object to the ManyToManyField. (I think this will simplify your relationships)
  2. If you really want to have this logic in db, create a middle table to save the relationship. You have your Mobile table and Imei table. Create another table to store the relationship of both, let's say MobielImei with following fields
class 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

Related Questions