Abhishek Goel
Abhishek Goel

Reputation: 3

how to add options in select field dynamically in django?

models.py

class Add_category(models.Model):
        Category = models.CharField(max_length=100)
        Image = models.ImageField()
        MetaKeyword = models.CharField(max_length=100)
        MetaDesc = models.CharField(max_length=100)

        def __str__(self):
        return self.Category

In this, I have tried to add city field and choices must come in this field by the help of Add_category model but it fails.

class Make_Invoice(models.Model):
        Order_no = models.IntegerField()
        Invoice_no = models.IntegerField()
        Product_name = models.CharField(max_length=100)
        Product_Id = models.IntegerField()
        Quantity = models.IntegerField()
        City = models.CharField(max_length=100, choices = Add_category.Category, default='Select')

Upvotes: 0

Views: 98

Answers (2)

Iain Shelvington
Iain Shelvington

Reputation: 32244

Use a ForeignKey

City = models.ForeignKey('Add_category', on_delete=models.PROTECT)

Upvotes: 1

Andrzej Długosz
Andrzej Długosz

Reputation: 336

Why even use City as a as a CharField? As far as I see it should be a ForeignKey - ManyToOne or even ManyToMany relation.

Check it in the documentation:

  1. https://docs.djangoproject.com/en/2.2/topics/db/examples/many_to_one/

  2. https://docs.djangoproject.com/en/2.2/topics/db/examples/many_to_many/

Upvotes: 2

Related Questions