'Django - Retrieve or get data from selected foreign key field

Relatively new to Django, I'm working on a Django project and attempting to retrieve particular foreign key object into variable when it's selected in Form.

model.py

class item_category(models.Model):
    idItemCat = models.CharField(primary_key=True max_length=5)
    nameCategory = models.CharField(max_length=150)

    def __str__(self):
        return self.nameCategory

class item_code(models.Model):
    idItemCat = models.ForeignKey(item_category, on_delete=models.DO_NOTHING)
    idItemCode = models.CharField(primary_key=True, editable=False, max_length=20)

    def __str__(self):
        return self.idItemCode 

I know I could retrieve object with making QuerySet such as .objects.last() and .objects.filter() or else, but it's just retrieve objects from database or existing data. What I'm about to do is, when a user submit a new data it'll retrieve particular foreign key object based on what I'm selected in this Form, so I could put into variable.

Any idea how should do it? it would be so much appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source