0

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)

2
  • It makes no sense to store something in the database, if the value is each time the same. Commented Aug 24, 2021 at 9:23
  • I asked this as an example. I am taking a pdf document as an input from the user using models.FileField(). And I have the code to extract the data from it. But I have no clue how to save it into the database. Commented Aug 24, 2021 at 9:56

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Barraguesh. Can I do this with my code from django.db import models class attempt(models.Model): name = models.TextField(max_length=200) def fun1(name): return(name+"some string") x = fun1(name) department = models.Charfield(max_length=100, default=x, editable=False)
@TharunTeja please update (edit) the original question with that question and code because it's hard to read code from a comment!
@TharunTeja The class is for models, functions can be implemented in the model, but have to be related to it, check out this example from the docs docs.djangoproject.com/en/3.2/topics/db/models/#model-methods. Also, if my answer is what you were looking for, you can select it as such with the tick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.