简体   繁体   中英

How do I add a default value to a variable and store in the database in django?

I'm very new to the Django framework. I've started working with models and forms in django. I'm facing a problem in storing values to a database.

I want to get something like this.

from django.db import models

class attempt(models.Model):
    name = models.TextField(max_length=200)
    department = "Software Development"

Now I want to store the variable department in the database. Where for every entry of object of attempt name will be entered by the user but department remains the same.

And is stored something like the below-given format in the database

id: 1
name: "John Shelby"
department: "Software Development" 

Edit 2: Now can I do something like this:

from django.db import models

class attempt(models.Model):
    name = models.TextField(max_length=200)
    def function1(str):
        return(str+" Hello World")
    x = function1(name)
    department = models.Charfield(max_length=100,default=x,editable=False)

You can use default , here's the documentation but basically what you want is:

department = models.Charfield(max_length=100, default="Software Development", editable=False)

This will make it that each time the model is created it will give it the default value in the department field. To prevent changes to said default value, I added the editable=False tag. Remove it in case you want to add other departments but have "Software Development" as the default one if no department is set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM