Lazy loading a model field's choices

markwalker_

I'm building a Django app to pull in data via an API to track live results of an event with the added ability to override that data before it is displayed.

The first task of the app is to make a request and store the response in the database so I've setup a model;

class ApiData(models.Model):
    event = models.CharField(
        _("Event"),
        max_length=100,
    )
    key = models.CharField(
        _("Data identifier"),
        max_length=255,
        help_text=_("Something to identify the json stored.")
    )
    json = JSONField(
        load_kwargs={'object_pairs_hook': collections.OrderedDict},
        blank=True,
        null=True,
    )
    created = models.DateTimeField()

Ideally I would like it so that objects are created in the admin and the save method populates the ApiData.json field after creating an API request based on the other options in the object.

Because these fields would have choices based on data returned from the API I wanted to lazy load the choices but at the moment I'm just getting a standard Charfield() in my form. Is this the correct approach for lazy loading model field choices? Or should I just create a custom ModelForm and load the choices there? (That's probably the more typical approach I guess)

def get_event_choices():
    events = get_events()
    choices = []
    for event in events['events']:
        choices.append((event['name'], event['title']),)
    return choices


class ApiData(models.Model):

    # Fields as seen above

    def __init__(self, *args, **kwargs):
        super(ApiData, self).__init__(*args, **kwargs)
        self._meta.get_field_by_name('event')[0]._choices = lazy(
            get_event_choices, list
        )()
markwalker_

So I went for a typical approach to get this working by simply defining a form for the model admin to use;

# forms.py
from django import forms

from ..models import get_event_choices, ApiData
from ..utils.api import JsonApi

EVENT_CHOICES = get_event_choices()


class ApiDataForm(forms.ModelForm):
    """
    Form for collecting the field choices.

    The Event field is populated based on the events returned from the API.
    """
    event = forms.ChoiceField(choices=EVENT_CHOICES)

    class Meta:
        model = ApiData

# admin.py
from django.contrib import admin

from .forms.apidata import ApiDataForm
from .models import ApiData


class ApiDataAdmin(admin.ModelAdmin):
    form = ApiDataForm


admin.site.register(ApiData, ApiDataAdmin)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

Lazy Loading vs Eager Loading

From Dev

Django model - changing options in a choices field and migrate

From Dev

Django: Access given field's choices tuple

From Dev

Django Multiple Levels Choices for Field

From Dev

Django RadioSelect Choices From Model

From Dev

django use model choices in modelform

From Dev

Lazy loading ViewPagers in a ScrollView

From Dev

How to create a virtual record field for Entity Framework lazy loading

From Dev

Lazy loading Pattern with Typescript

From Dev

Use custom where clause on EF's Lazy Loading

From Dev

Lazy loading in uicollectionview

From Dev

Changing the choices in Django Model according to a field value

From Dev

Delphi - is it possible to disable Delphi's lazy loading of forms?

From Dev

One Django model field as array of strings and another field as dropdown with choices from first field?

From Dev

class for model choices

From Dev

Convert a Django Model Field Choices into a JSON

From Dev

FieldError: Invalid field name(s) given in select_related: 'userinfo'. Choices are: userinfo

From Dev

What is Django model field choices best practices?

From Dev

How can Lazy<T> provide thread safe lazy loading when it's .value property does not lock?

From Dev

Lazy loading a model field's choices

From Dev

Spring, Hibernate, JPA: Lazy loading id's

From Dev

Eloquent/Laravel: Nested lazy eager loading, but return multiple model's relations

From Dev

Django field choices not properly updating

From Dev

Populate Django <select> <option>s from model's rows, not its CHOICES

From Dev

Dynamically set field choices for article

From Dev

Django model with multiple choices

From Dev

Models list as choices in a Model

From Dev

django - admin model assign value to limit_choices_to from another field inside the model

From Dev

Create instance of model with field with choices

Related Related

  1. 1

    Lazy Loading vs Eager Loading

  2. 2

    Django model - changing options in a choices field and migrate

  3. 3

    Django: Access given field's choices tuple

  4. 4

    Django Multiple Levels Choices for Field

  5. 5

    Django RadioSelect Choices From Model

  6. 6

    django use model choices in modelform

  7. 7

    Lazy loading ViewPagers in a ScrollView

  8. 8

    How to create a virtual record field for Entity Framework lazy loading

  9. 9

    Lazy loading Pattern with Typescript

  10. 10

    Use custom where clause on EF's Lazy Loading

  11. 11

    Lazy loading in uicollectionview

  12. 12

    Changing the choices in Django Model according to a field value

  13. 13

    Delphi - is it possible to disable Delphi's lazy loading of forms?

  14. 14

    One Django model field as array of strings and another field as dropdown with choices from first field?

  15. 15

    class for model choices

  16. 16

    Convert a Django Model Field Choices into a JSON

  17. 17

    FieldError: Invalid field name(s) given in select_related: 'userinfo'. Choices are: userinfo

  18. 18

    What is Django model field choices best practices?

  19. 19

    How can Lazy<T> provide thread safe lazy loading when it's .value property does not lock?

  20. 20

    Lazy loading a model field's choices

  21. 21

    Spring, Hibernate, JPA: Lazy loading id's

  22. 22

    Eloquent/Laravel: Nested lazy eager loading, but return multiple model's relations

  23. 23

    Django field choices not properly updating

  24. 24

    Populate Django <select> <option>s from model's rows, not its CHOICES

  25. 25

    Dynamically set field choices for article

  26. 26

    Django model with multiple choices

  27. 27

    Models list as choices in a Model

  28. 28

    django - admin model assign value to limit_choices_to from another field inside the model

  29. 29

    Create instance of model with field with choices

HotTag

Archive