how to make django model run some function when create

  • Last Update :
  • Techknowledgy :

Just eliminate if kwargs['created'] and call do_something() right in the body of a function:

def model_created_or_updated(sender, ** kwargs):
   the_instance = kwargs['instance']
do_something()

post_save.connect(model_created_or_updated, sender = YourModel)

Suggestion : 2

To create a new instance of a model, instantiate it like any other Python class:,The keyword arguments are the names of the fields you’ve defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save().,In addition to creating the new model, the from_db() method must set the adding and db flags in the new instance’s _state attribute.,A helper method that returns a set containing the attribute names of all those fields that are currently deferred for this model.

from django.db
import models

class Book(models.Model):
   title = models.CharField(max_length = 100)

@classmethod
def create(cls, title):
   book = cls(title = title)
# do something with the book
return book

book = Book.create("Pride and Prejudice")
class BookManager(models.Manager):
   def create_book(self, title):
   book = self.create(title = title)
# do something with the book
return book

class Book(models.Model):
   title = models.CharField(max_length = 100)

objects = BookManager()

book = Book.objects.create_book("Pride and Prejudice")
from django.db.models
import DEFERRED

@classmethod
def from_db(cls, db, field_names, values):
   # Default implementation of from_db()(subject to change and could # be replaced with super()).
if len(values) != len(cls._meta.concrete_fields):
   values = list(values)
values.reverse()
values = [
   values.pop() if f.attname in field_names
   else DEFERRED
   for f in cls._meta.concrete_fields
]
instance = cls( * values)
instance._state.adding = False
instance._state.db = db
# customization to store the original field values on the instance
instance._loaded_values = dict(
   zip(field_names, (value
      for value in values
      if value is not DEFERRED))
)
return instance

def save(self, * args, ** kwargs):
   # Check how the current values differ from._loaded_values.For example,
   # prevent changing the creator_id of the model.(This example doesn 't
      # support cases where 'creator_id'
      is deferred).
if not self._state.adding and(
      self.creator_id != self._loaded_values['creator_id']):
   raise ValueError("Updating the value of creator isn't allowed")
super().save( * args, ** kwargs)
>>> obj = MyModel.objects.first() >>>
   del obj.field >>>
   obj.field # Loads the field from the database
def test_update_result(self):
   obj = MyModel.objects.create(val = 1)
MyModel.objects.filter(pk = obj.pk).update(val = F('val') + 1)
# At this point obj.val is still 1, but the value in the database
# was updated to 2. The object 's updated value needs to be reloaded
# from the database.
obj.refresh_from_db()
self.assertEqual(obj.val, 2)
class ExampleModel(models.Model):
   def refresh_from_db(self, using = None, fields = None, ** kwargs):
   # fields contains the name of the deferred field to be
# loaded.
if fields is not None:
   fields = set(fields)
deferred_fields = self.get_deferred_fields()
# If any deferred field is going to be loaded
if fields.intersection(deferred_fields):
   # then load all of them
fields = fields.union(deferred_fields)
super().refresh_from_db(using, fields, ** kwargs)

Suggestion : 3

Last modified: Jul 11, 2022, by MDN contributors

from django.db
import models
from django.urls
import reverse

class MyModelName(models.Model):
   ""
"A typical class defining a model, derived from the Model class."
""

# Fields
my_field_name = models.CharField(max_length = 20, help_text = 'Enter field documentation')
#…

# Metadata
class Meta:
   ordering = ['-my_field_name']

# Methods
def get_absolute_url(self):
   ""
"Returns the URL to access a particular instance of MyModelName."
""
return reverse('model-detail-view', args = [str(self.id)])

def __str__(self):
   ""
"String for representing the MyModelName object (in Admin site etc.)."
""
return self.my_field_name
my_field_name = models.CharField(max_length = 20, help_text = 'Enter field documentation')
class CatalogConfig(AppConfig):
   default_auto_field = 'django.db.models.BigAutoField'
class Meta:
   ordering = ['-my_field_name']
ordering = ['title', '-pubdate']
verbose_name = 'BetterName'

Suggestion : 4

In this shot, we look into how to create an instance of a table in the database using a function-based view in Django.,This file is used to create functions or classes that visualize how a route will operate.,In case you want to create a super-user, run the following command:,In this file, we register our model that has been created by importing it. By doing so, we can see it when logged in as an admin.

pip is a package manager for Python packages.

pip install pipenv
pipenv shell
pipenv install django
pip install pipenv
pipenv shell
pipenv install django
django - admin startproject crud. /

   python manage.py startapp codebase
django-admin startproject crud ./

python manage.py startapp codebase
python manage.py migrate

python manage.py runserver
INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',

   'codebase'
]
from django.db
import models
from django.urls
import reverse

class CRUD(models.Model):
   name = models.CharField(max_length = 30)
age = models.IntegerField()
level = models.CharField(max_length = 30)
date = models.DateTimeField(auto_now_add = True)

#display the data with name
def __str__(self):
   return self.name
from django.contrib
import admin
from.models
import CRUD

admin.site.register(CRUD)
from django
import forms
from.models
import CRUD

class CRUDFORM(forms.ModelForm):
   name = forms.CharField(widget = forms.TextInput(attrs = {
      "class": "form-control",
      "placeholder": "name"
   }))
age = forms.CharField(widget = forms.TextInput(attrs = {
   'type': "number",
   "class": "form-control",
   "placeholder": "age"
}))

level = forms.CharField(widget = forms.TextInput(attrs = {
   "class": "form-control",
   "placeholder": "level"
}))
class Meta:
   model = CRUD
fields = [
   'name', 'age', 'level'
]
from django.shortcuts
import redirect, render, get_object_or_404
from.models
import CRUD
from.forms
import CRUDFORM

def home(request):
   queryset = CRUD.objects.all().order_by('-date')
context = {
   'queryset': queryset
}
return render(request, 'app/base.html', context)

def create(request):
   form = CRUDFORM(request.POST or None)

if request.method == "POST":
   if form.is_valid():
   form.save()
return redirect('home')
context = {
   "form": form
}
return render(request, 'app/createform.html', context)

Suggestion : 5

jQuery Tutorial ,django syncdb and an updated model

Just eliminate if kwargs['created'] and call do_something() right in the body of a function:

def model_created_or_updated(sender, ** kwargs):
   the_instance = kwargs['instance']
do_something()

post_save.connect(model_created_or_updated, sender = YourModel)

Suggestion : 6

I have decided to concentrate on other projects, so the djangobook domain will pass back to the Django community in the next couple of months.,Extra manager methods are created by inheriting the Manager base class and adding custom functions to the custom Manager class. For example, let’s create an extra manager method for the Event model to retrieve the total number of events for a particular event type (changes in bold):,Let’s use the Django interactive shell to explore a few examples of the more common QuerySet methods not already covered in the book.,Let’s return to the Django interactive shell to dig deeper into some common examples not already covered in the book.

exclude() will return a QuerySet of objects that don’t match the given lookup parameters, for example:

>>> from events.models import Venue
>>> Venue.objects.exclude(name="South Stadium")
<QuerySet [<Venue: West Park>, <Venue: North Stadium>, <Venue: East Park>]>

Using more than one lookup parameter will use an SQL AND operator under the hood:

>>> from events.models import Event
>>> from datetime import datetime, timezone
>>> venue1 = Venue.objects.get(name="East Park")
>>> Event.objects.exclude(venue=venue1,event_date=datetime(2020,23,5,tzinfo=timezone.utc))
<QuerySet [<Event: Test Event>, <Event: Club Presentation - Juniors>, <Event: Club Presentation - Seniors>, <Event: Gala Day>]>

Annotations can be simple values, a field reference or an aggregate expression. For example, let’s use Django’s Count aggregate function to annotate our Event model with a total of all users attending each event:

>>> from events.models
import Event
   >>>
   from django.db.models
import Count
   >>>
   qry = Event.objects.annotate(total_attendees = Count('attendees')) >>>
   for event in qry:
   ...print(event.name, event.total_attendees)
   ...
   Test Event 0
Gala Day 2
Club Presentation - Juniors 5
Club Presentation - Seniors 3 >>>

Or ordering can be multi-level. In the following example, the events are first ordered by event date and then by event name:

>>> Event.objects.all().order_by('event_date','name')
<QuerySet [<Event: Club Presentation - Juniors>, <Event: Club Presentation - Seniors>, <Event: Gala Day>, <Event: Test Event>]>

By default, QuerySet fields are ordered in ascending order. To sort in descending order, use the - (minus) sign:

>>> Event.objects.all().order_by('-name')
<QuerySet [<Event: Test Event>, <Event: Gala Day>, <Event: Club Presentation - Seniors>, <Event: Club Presentation - Juniors>]>