How to store list of foreign keys in a model

Viewed 111

Hii Everyone here is the case in which i am facing this same issue please have a look over this:

ClassificationGroup.py

class DeviceClassificationGroup:
    vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True)
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=1000)
    classification = ??

Classification.py

class DeviceClassification(models.Model):
    vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True)
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=1000)
    device_type = models.IntegerField()
    device_name_regex = models.CharField(max_length=100)
    vid_pid = models.CharField(max_length=50)
    device_instance_id = models.CharField(max_length=100)
    serial_number = models.CharField(max_length=100)
    brand = models.CharField(max_length=25)

    def __str__(self):
        return self.name

So i would have set of classifications that i can put in the one classification group.

How can i store an unknown amount of foreign keys in a django model??

Kindly help me out in this.

2 Answers

By adding a ForeignKey field to the DeviceClassification model:

class DeviceClassification(models.Model):
  group = models.ForeignKey(DeviceClassificationGroup, on_delete=models.CASCADE, related_name='classifications')

Remember, that adding a foreign key to a model creates a One-To-Many relationship, meaning that one DeviceClassification belongs to one DeviceClassificationGroup, and a DeviceClassificationGroup can have many DeviceClassification objects associated with it.

If you now want to access your DeviceClassification objects from an DeviceClassificationGroup instance:

group.classifications.all()

Note that the accessor is the same as specified as related_name in the model.

If you do not specify a related_name, it will be auto-chosen as <model_name>_set. If you do not want a related name, you can use +.

Docs: Related Name

i think you might looking for built a relationships between DeviceClassification & DeviceClassificationGroup where one group may have multiple classification

So just use like this

class DeviceClassification(models.Model):
  group = models.ForeignKey(DeviceClassificationGroup, on_delete=models.CASCADE)

So after applying this if you run DeviceClassificationGroup.classification you'll get all the classification list

If you want to learn in depth you can check this link

Related