zaidan
zaidan

Reputation: 23

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.

Upvotes: 2

Views: 2959

Answers (1)

raphael
raphael

Reputation: 2880

You really should look at the Django Docs on forms. They are excellent, and will teach you the right way to handle forms, a complicated topic.

To answer your question directly, it looks like you already have the html part, and as long as it has the form tag, like this:

<form action='your_view' method='post'>
    ...
</form>

Then in your view you could do something like this:

def your_view(request):
    if request.method == 'POST':
        category = item_category.objects.get(pk=request.POST.get('name_attribute_of_your_input'))

I'd need to see more specifics to give you a better answer, but there are several issues you should fix first.

First, your class names should be capitalized, field names lower case, and second,are you sure you want to make a CharField the primary key? You can, but for most cases, the automatically generated integer pk that Django creates is best.

class ItemCategory(models.Model):
    # Django will create an integer pk for you
    # idItemCat = models.CharField(primary_key=True max_length=5)
    nameCategory = models.CharField(max_length=150)

    def __str__(self):
        return self.nameCategory

class ItemCode(models.Model):
    idItemCat = models.ForeignKey(ItemCategory, on_delete=models.DO_NOTHING)
    # Again, just let Django generate the primary key
    # idItemCode = models.CharField(primary_key=True, editable=False, max_length=20)

    def __str__(self):
        return self.idItemCode 

Upvotes: 1

Related Questions