0

The code starts below, specifically for models and views -

class userchoice(models.Model):
choice = []
choice2 = list(userdata.objects.all().values_list('key'))
for x in choice2:
    for t in x:
        choice.append((t,t.capitalize()))

Job_ID = models.CharField(primary_key = True, max_length=200, choices=choice, default='key')
Group_ID= models.CharField(max_length=200, choices=choice, default='key')
Customer_name = models.CharField(max_length=200, choices=choice, default='key')
Planned_Duration = models.CharField(max_length=200, choices=choice, default='key')
Worker_name = models.CharField(max_length=200, choices=choice, default='key')
Job_note = models.CharField(max_length=200, choices=choice, default='key')
Customer_tp_name = models.CharField(max_length=200, choices=choice, default='key')

from django.db import migrations, models

class Migration(migrations.Migration):

dependencies = [
    ('csvfileapp', '0008_userdata'),
]

operations = [
    migrations.CreateModel(
        name='userchoice',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('Job_ID', models.CharField(default='key', max_length=200)),
            ('Group_ID', models.CharField(default='key', max_length=200)),
            ('Customer_name', models.CharField(default='key', max_length=200)),
            ('Planned_Duration', models.CharField(default='key', max_length=200)),
            ('Worker_name', models.CharField(default='key', max_length=200)),
            ('Job_note', models.CharField(default='key', max_length=200)),
            ('Customer_tp_name', models.CharField(default='key', max_length=200)),
        ],
    ),
]

1 Answers1

0

By far, it's not a good solution at all. because choices can change anytime (because it's fetching database result) so any change lead to new migration file which is not good. Do as follow:

  • just remove that part, make it a simple charField
  • in your forms.py initiate the field that you want to have choices with the database query results you want.

To sum up, handle this situation in views and forms, not database orm and migrations!

Update:

Here's a code sample of forms.py to use:

class waypointForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ChoiceField(
            choices=[(o.id, str(o)) for o in     Waypoint.objects.filter(user=user)]

here's the stack link for it

Reza Torkaman Ahmadi
  • 2,958
  • 2
  • 20
  • 43