1

I am trying to set the choices for a Child field equal to two choices that are fields that come from the Parent class that it's related to (each child only has one parent). How do I access these values?

 class Parent(models.Model):
        attribute1 = models.CharField(max_length=100)
        attribute2 = models.CharField(max_length=100)
    

class Child(models.Model):

    choices_in = ((WHAT TO PUT HERE, WHAT TO PUT HERE), (WHAT TO PUT HERE, WHAT TO PUT HERE))  

    parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
    item = models.CharField(max_length=100, null=True, choices=choices_in)
bernardo
  • 173
  • 8
  • Do you mean that you want the choices for the `item` field to be from fields of the `Parent` model? – markwalker_ Dec 29 '20 at 23:27
  • @markwalker_ i want it to choose between two attributes from parent – bernardo Dec 29 '20 at 23:28
  • You'd have to create your own forms which perform the query to generate the choices in the form's `__init__` method – markwalker_ Dec 29 '20 at 23:31
  • @markwalker_ like in forms.py? – bernardo Dec 29 '20 at 23:33
  • That's right. You'd need to setup a custom form for admin and anywhere else that you want to use this. – markwalker_ Dec 29 '20 at 23:35
  • You could try [model methods](https://docs.djangoproject.com/en/3.1/topics/db/models/#model-methods) to generate sequences from the other model. However, the choices must change as the Parent has more instances, the choices must reflect as well(I presume), hence why @markwalker_ suggested forms – Mugoma Dec 29 '20 at 23:38
  • @markwalker_ I'm a bit confused as to why it requires a form. I'm just trying to pass in a value? – bernardo Dec 29 '20 at 23:38
  • It's because you'll have to run a query on the tables in order to generate the choices. You can't do that in a model. – markwalker_ Dec 29 '20 at 23:44
  • @markwalker_ I'm relatively new to Django. In the past I've used a UserCreationForm and forms.modelForm. For this, what template or guide should I follow? Thanks for all of your help! – bernardo Dec 30 '20 at 00:26
  • Have a look at this question, it looks rather similar; https://stackoverflow.com/questions/3419997/creating-a-dynamic-choice-field – markwalker_ Dec 30 '20 at 00:30

0 Answers0