-
-
Save bradmontgomery/1c52b799c4ad274e0cbdd012a8b18f10 to your computer and use it in GitHub Desktop.
# Here's your list of choices that would be displayed in a drop-down | |
# element on the web. It needs to be a tuple, and we define this | |
# as a variable just for readability/convenience. | |
# | |
# This example has 3 choices, each of which consists of two parts: | |
# 1. the thing that get strored in your database | |
# 2. the thing that you see in a dropdown list | |
LABEL_CHOICES = ( | |
('this gets stored in your database', 'This item is what you see in the drop-down'), | |
('django', 'Django'), | |
('python', 'Python'), | |
) | |
class Post(models.Model): | |
# Now, when you define your ArrayField's base field (in this case a CharField), | |
# you can specify the list of choices that will be precented to the user. | |
# Use: choices=LABEL_CHOICES | |
labels = ArrayField( | |
models.CharField(max_length=32, blank=True, choices=LABEL_CHOICES), | |
default=list, | |
blank=True, | |
) |
How do you use get_foo_display() for labels field as choices is nested inside an array?
That's a great question @sauravkhakurel, and I haven't implemented this, but I think you'd need to override get_foo_display()
for your model so that it returned a list of the "display" values. Continuing with the Post
example from above, it might look something like this:
class Post(models.Model):
# Now, when you define your ArrayField's base field (in this case a CharField),
# you can specify the list of choices that will be precented to the user.
# Use: choices=LABEL_CHOICES
labels = ArrayField(
models.CharField(max_length=32, blank=True, choices=LABEL_CHOICES),
default=list,
blank=True,
)
def get_labels_display(self):
lookup = {v: k for k, v in LABEL_CHOICES}
return [lookup.get(v, "unknown") for v in self.labels]
How do you use get_foo_display() for labels field as choices is nested inside an array?
That's a great question @sauravkhakurel, and I haven't implemented this, but I think you'd need to override
get_foo_display()
for your model so that it returned a list of the "display" values. Continuing with thePost
example from above, it might look something like this:class Post(models.Model): # Now, when you define your ArrayField's base field (in this case a CharField), # you can specify the list of choices that will be precented to the user. # Use: choices=LABEL_CHOICES labels = ArrayField( models.CharField(max_length=32, blank=True, choices=LABEL_CHOICES), default=list, blank=True, ) def get_labels_display(self): lookup = {v: k for k, v in LABEL_CHOICES} return [lookup.get(v, "unknown") for v in self.labels]
Thanks for the answer. I got help from a colleague and did something similar to this to solve the problem that I had at hand.
How do you use get_foo_display() for labels field as choices is nested inside an array?
Thanks