Home > Mobile >  How to call call a static function from the same Model in the Model upon initialisation? DJANGO PYTH
How to call call a static function from the same Model in the Model upon initialisation? DJANGO PYTH

Time:08-19

So long story short, I have a Car model and a CarVersion model and I want the user to have the ability to choose from the availble car versions saved in the database, through a html select field.

I cannot understand how to dynamically generate the choices field from the CarVersion model. I have the function, but I cannot call it inside the Car model.

Here is the code I have so far:

class Car(models.Model):
    choices = get_choices()

    name = models.CharField(max_length=50, unique=True)
    version = models.ForeignKey(CarVersion, choices=get_choices(), on_delete=models.RESTRICT)
    
    @staticmethod
    def get_choices():
        options = CarVersion.objects.all().values_list("pk", "name")
        try:
            if not options:
                return [(0, "No versions in database. Call your administrator.")]
        except ProgrammingError:
            return [(0, "No versions in database. Call your administrator.")]
        return [(1, "Test")]

I want to call the function get_choices in

version = models.ForeignKey(CarVersion, choices=get_choices(), on_delete=models.RESTRICT) but I don't know how to do that while the function is declared to the model. If I define it outside of the model, it works, but there must surely be a better way that im missing, rather than cluttering my models.py file with a bunch of model specific functions.

P.S.get_choices is not finished but as soon as I can call it, I will deal with it.

CodePudding user response:

I would advise against doing it this way for several reasons. The choices parameter on the model field is for validating data you could potentially add to the database.

Besides that, the way yo write it, the function that fetches the CarVersion objects is called when the module is loaded. This is a bad idea. You may want to import the module in some place at a time when you don't even have a database connection yet.

The proper way to to this, since your intent is to generate options in an HTML form for the user, would be to rely on the foreign key capabilities of the Django Forms. The ModelChoiceField should already do what you need.

PS: In fact the ModelChoiceField is automatically instantiated, when you create a ModelForm from a Model that has a ForeignKey field. See the list of field conversion on the ModelForm page.

CodePudding user response:

I want to thank Daniil for his contribution, for without it, I would have never been able to ask the correct question for my problem, which is:

How to dynamically generate a choices field.

The answer to that question can be found at: How to create a dynamic Django choice field

  • Related