简体   繁体   中英

How to set Django model default value equal to result of a query

I'm quite new at Django, and trying to create a model where det default value for Foreign Keys user and department are set to the correct values for the logged in user. Normally I use the request object and queries the database, but in the model definition I don't know how to do this. I suppose a path forward is to make default value a function and make the query in the function, but I am stuck. Any help are greatly appreciated. Here is an example of my code:

from django.contrib.auth import get_user_model
from django.db import models
from another_app.models import Department, DepartmentPermissions

class Article(models.Model):
    header = models.CharField(max_length=200)
    text = models.CharField(max_length=800)
    owner = models(get_user_model(), related_name='owner_article', on_delete=models.PROTECT)
    department = models.ForeignKey(Department, on_delete=models.CASCADE) #here I want it defaulted to DepartmentPermissions.objets.get(user= <logged in user>)[0].department

Well it is possible but not from the model but from the admin. So, you can do:

from django.contrib.auth import get_user_model
from django.db import models
from another_app.models import Department, DepartmentPermissions

# import admin
from django.contrib import admin

class Article(models.Model):
    header = models.CharField(max_length=200)
    text = models.CharField(max_length=800)
    owner = models(get_user_model(), related_name='owner_article', on_delete=models.PROTECT)
    department = models.ForeignKey(Department, on_delete=models.CASCADE) 

class ArticleAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.department = request.user
        obj.save()

Now, it will act like default because, when you save to model, the value will be saved from save_model

It is not possible. That is your part of business logic. You should do it in your View , or Validator (if you use Django Rest Framework)

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