Creation of dynamic model fields in django

前端 未结 4 1240
别那么骄傲
别那么骄傲 2020-12-07 10:12

This is a problem concerning django. I have a model say \"Automobiles\". This will have some basic fields like \"Color\",\"Vehicle Owner Name\", \"Vehicle Cost\".

I

4条回答
  •  星月不相逢
    2020-12-07 10:26

    Are you talking about in a front end interface, or in the Django admin?

    You can't create real fields on the fly like that without a lot of work under the hood. Each model and field in Django has an associated table and column in the database. To add new fields usually requires either raw sql, or migrations using South.

    From a front end interface, you could create pseudo fields, and store them in a json format in a single model field.

    For example, create an other_data text field in the model. Then allow users to create fields, and store them like {'userfield':'userdata','mileage':54}

    But I think if you're using a finite class like vehicles, you would create a base model with the basic vehicle characteristics, and then create models that inherits from the base model for each of the vehicle types.

    class base_vehicle(models.Model):
        color = models.CharField()
        owner_name = models.CharField()
        cost = models.DecimalField()
    
    class car(base_vehicle):
        mileage = models.IntegerField(default=0)
    

    etc

提交回复
热议问题