Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model choice field from another model instance

In my models.py, I have two classes, ChoiceList and SampleModel as below

class ChoiceList(models.Model):
    choice=models.CharField(max_length=15)

class SampleModel(models.Model):
    CHOICELIST=ChoiceList.objects.all()
    name=models.CharField(max_length=15)
    your_choice=models.CharField(max_length=15,choices=ChoiceList)

I need to add your_choice field data only from ChoiceList instances. Can I add data in that way ?

When I doing this way, I got error as django.db.utils.OperationalError: no such table: rest_api_ChoiceList
Can anyone solve the problem ?

like image 390
JPG Avatar asked Aug 01 '17 17:08

JPG


People also ask

How do you create an instance of a model from another model in Django?

To create a new instance of a model, instantiate it like any other Python class: class Model (**kwargs) The keyword arguments are the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save() .

How do you add a new field to a model with new Django migrations?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB. Save this answer.

What is __ str __ In Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model.

What is Onetoone field in Django?

This field can be useful as a primary key of an object if that object extends another object in some way. For example – a model Car has one-to-one relationship with a model Vehicle, i.e. a car is a vehicle. One-to-one relations are defined using OneToOneField field of django.


Video Answer


1 Answers

you should use ForeignKey()

your_choice=models.ForeignKey(ChoiceList,on_delete=models.CASCADE)
like image 112
badiya Avatar answered Oct 21 '22 13:10

badiya