This is my Django Models.py
class Test1(models.Model):
id = models.AutoField(db_column='Id', primary_key=True)
name = models.TextField(db_column='Name', blank=True, null=True)
class Test2(models.Model):
id = models.AutoField(db_column='Id', primary_key=True)
sequence = models.IntegerField(db_column='Sequence')
test1id = models.ForeignKey('Test1', models.DO_NOTHING,null=False, db_column='Test1Id')
what i am trying to do is to ensure when the Test1 id is saved, it automatically fills in the test1id.
Not sure what you want to do here, but if you want to implement any post save actions for model look at django signals. Particularly at post_save signal.
Here is example usage of post_save signal, for model Test1(suppose you want to create new Test2 object):
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=Test1)
def create_test2(sender, instance, created, **kwargs):
Test2.objects.create(test1id=instance)
You can redefine the save method:
def save(self, **kwargs):
if self.pk is None:
super(Test1, self).save()
Test2.objects.create(test1id=self)
else:
super(Test1, self).save()
So when you save Test1, a Test2 entry is created
Related
Automatically delete an object from the database if one attribute of the object is TRUE.
I've tried Django Signals, but it didn't help.
class Question(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
question = models.TextField(max_length=200)
answered = models.BooleanField(default=False)
def __str__(self):
return self.name
If I change the "answered" field to TRUE in Admin Panel, then this object must be automatically deleted from the database.
You will need post_save signals by using something like:
from .models import Question
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=Question)
def save_profile(sender, instance, **kwargs):
if instance.answered:
instance.delete()
We would like to access related ManyToManyField data pre-save within the Model.save method, however the data isn't available yet via the Django ORM because it's related ManyToManyField data and doesn't get set until post-save of the primary record.
Here's some example code of the relationship and where the related ManyToMany records are accessed in Model.save
class Friend(models.Model):
name = models.CharField(max_length=50)
class Person(models.Model):
name = models.CharField(max_length=50)
friends = models.ManyToManyField(Friend)
def save(self, *args, **kwargs):
friends = self.friends.all()
# 'friends' is an empty QuerySet at this point
# I'd like to do something with friends here,
# but it gets set after save
super(Friend, self).save(*args, **kwargs)
Example use case where friends are passed in on save:
friend = Friend.objects.all()[0]
friend2 = Friend.objects.all()[1]
friends = [friend, friend2]
Person.objects.create(friends=friends)
m2m relations establish after instance saved and get it's own id,so you can't access it within override save method,two way to archieve:
one: after django 1.9,transaction tools provide new method to listen db communication,doc is here.demo code is:
from django.db import transaction
class Person(models.Model):
name = models.CharField(max_length=50)
friends = models.ManyToManyField(Friend)
def save(self, *args, **kwargs):
instance = super(Person, self).save(*args, **kwargs)
transaction.on_commit(self.update_friend)
return instance
def update_friend(self):
for friend in self.friends.all():
print(friend.__str__())
second way is use signal,here is demo:
from django.db.models.signals import m2m_changed
#receiver(m2m_changed, sender=Person.friends.through)
def friends_change(sender, action, pk_set, instance=None, **kwargs):
if action in ['post_add', 'post_remove']:
queryset = instance.friends.all()
for friend in queryset:
print(friend.__str__())
I would like to run some code specifically when the is_active field is changed for a Django User, similar to how the save method works for other models:
class Foo(models.Model):
...
def save(self, *args, **kwargs):
if self.pk is not None:
orig = Foo.objects.get(pk=self.pk)
if orig.is_active != self.is_active:
# code goes here
Can this be done through another model that is in one to one relation with the User model? Something like:
class Bar(models.Model):
owner = models.OneToOneField(User, on_save=?)
...
I guess I could duplicate the is_active field on the related model and then set the is_active field on the User when saving the related model. But this seems like a bit of a messy solution.
You're looking for this Signal
from django.db.models.signals import pre_save
from django.contrib.auth.models import User
def do_your_thing(sender, instance, **kwargs):
# Do something
print(instance)
pre_save.connect(do_your_thing, sender=User)
I am trying to create a model in which I have a case_id field. This field should be auto incrementing. But my case_id value should be in the format shown,
case_id=FAS150001 (This should be the first value)
class InformationRequest(models.Model):
"""Model to track information"""
case_id = models.CharField(max_length=50)
user = models.ForeignKey(User)
information = models.TextField()
How can I do this?
Charfields cannot be auto-incremented.
But Django signals can help you to simulate this behavior. You could do a pre-save or post-save signal for make it, for example:
from django.db.models.signals import pre_save
from django.dispatch import receiver
from myapp.models import InformationRequest
#receiver(pre_save, sender=InformationRequest)
def my_handler(sender, instance=None, **kwargs):
# Compute case_id, ex:
# instance.case_id = increment_case_id()
I need to create an instance of my model every time a new group has been created in the admin panel.
I read some information about signals, but i can't figured it out at all.
Thank you very much
models.py with your model:
from django.db import models
from django.contrib.auth.models import Group
from django.db.models.signals import post_save
class YourModel(models.Model):
name = models.CharField('name', max_length=50)
group = models.ForeignKey(Group)
# ...
#classmethod
def create_after_group(cls, sender, instance, created, **kwargs):
if created:
group_created = instance
m = cls(name="Some name", group=group_created)
m.save()
post_save.connect(YourModel.create_after_group, sender=Group)