Getting ID of newly created object in save() - django

I want to save an object, so that the M2M get saved. Then I want to read out the M2M fields to do some calculations and set a field on the saved object.
class Item(models.Model):
name = models.CharField(max_length=20, unique=True)
product = models.ManyToManyField(SomeOtherModel, through='SomeTable')
def save(self, *args, **kwargs):
super(Item, self).save(*args, **kwargs)
m2m_items = SomeTable.objects.filter(item = self)
# DO SOME STUFF WITH THE M2M ITEMS
The m2m_items won't turn up,. Is there any way to get these up ?

Some confusion here.
Once you've called super, self.id will have a value.
However, I don't understand the point of your filter call. For a start, you probably mean get rather than filter anyway, as filter gets a queryset, rather than a single instance. But even so, the call is pointless: you've just saved it, so whatever you get back from the database will be exactly the same. What's the point?
Edit after question update OK, thanks for the clarification. However, the model's save() method is not responsible for doing anything with M2M items. They need to be saved separately, which is the job of the form or the view.

Related

Django formset save() writes new object on database?

So I have MyModel:
class MyModel(models.Model):
name = models.CharField(_('Name'), max_length=80, unique=True)
...
def save(self, *args, **kwargs):
if MyModel.objects.count() >= 5:
raise ValidationError("Can not have more than 5 MyModels!")
super().save(*args, **kwargs) # Call the "real" save() method.
There are already 5 objects from MyModel on the database.
I have a page where I can edit them all at the same time with a formset.
When I change one or more of them, I will get the Validation Error "Can not have more than 5 MyModels!".
Why is this happenning? I tought the formset was supposed to edit the existing objects, but it appears to be writing a new one and deleting the old one.
What is really happening when I do a formset.save() on the database?
Do I have to remove the save() method?
The save method inside the Model is called regardless you are creating or editing. Although you can distinguish between them by checking if the object has a primary key, like this:
if not self.pk and MyModel.objects.count() >= 5:
If you want more sophisticated control over validation, I suggest putting them in the forms. Specially if you want to limit the number of formset, you can check this documentation.

Override Default Save Method And Create Duplicate

I am looking to create a duplicate instance each time a user tries to update an instance. The existing record is untouched and the full update is saved to the new instance.
Some foreign keys and reverse foreign keys must also be duplicated. The Django documentation
talks about duplicating objects, but does not address reverse foreign keys.
Firstly, is there an accepted way of approaching this problem?
Secondly, I am unsure whether it's best to overwrite the form save method or the model save method? I would want it to apply to everything, regardless of the form, so I assume it should be applied at the model level?
A simplified version of the models are outlined below.
class Invoice(models.Model):
number = models.CharField(max_length=15)
class Line(models.Model):
invoice = models.ForeignKey(Invoice)
price = models.DecimalField(max_digits=15, decimal_places=4)
Here's my shot at it. If you need it to duplicate every time you make any changes, then override the model save method. Note that this will not have any effect when executing .update() on a queryset.
class Invoice(models.Model):
number = models.CharField(max_length=15)
def save(self, *args, **kwargs):
if not self.pk:
# if we dont have a pk set yet, it is the first time we are saving. Nothing to duplicate.
super(Invoice, self).save(*args, **kwargs)
else:
# save the line items before we duplicate
lines = list(self.line_set.all())
self.pk = None
super(Invoice, self).save(*args, **kwargs)
for line in lines:
line.pk = None
line.invoice = self
line.save()
This will create a duplicate Invoice every time you call .save() on an existing record. It will also create duplicates for every Line tied to that Invoice. You may need to do something similar every time you update a Line as well.
This of course is not very generic. This is specific to these 2 models. If you need something more generic, you could loop over every field, determine what kind of field it is, make needed duplicates, etc.

self.delete() gives error: "instance needs to have a primary key value before a many-to-many relationship can be used"

I have three models. We'll call them Mod1, Mod1Request, and UserProfile.
Mod1Request looks like:
class Mod1Request(models.Model):
date_requested = models.DateField(auto_now_add=True)
mod1s = models.ManyToManyField('Mod1')
user = models.ForeignKey(User)
approved = models.BooleanField()
def save(self, *args, **kwargs):
if self.approved:
for c in list(self.mod1s.all()):
mod = mod1.objects.get(id=c.id)
self.user.get_profile().mod1s.add(mod)
self.delete()
else:
super(Mod1Request, self).save(*args, **kwargs)
And then the UserProfile has a 'mod1s' attribute that is a ManyToManyField to Mod1. What I'm trying to accomplish is this:
When a Mod1Request is saved, if Approved is set then have the Mod1s listed in the Mod1Request added to UserProfile and then delete the Mod1Request itself.
This functionality works right up until it goes to delete itself. If I remove the self.delete() line then the Mod1 instances in Mod1Request are correctly added to UserProfile.mod1s. However, if I leave it in I get the following error:
'Mod1Request' instance needs to have a primary key value before a many-to-many relationship can be used.
Any help would be greatly appreciated.
EDIT: I should clarify that the Mod1Request gets entered by one user in a form and then approved by another (admin) user. So the admin user checks approved and 'saves' the Mod1Request. The Mod1Request should then add the Mod1s to the UserProfile and delete itself.
Just remove self.delete() - you don't need it. Because you're not calling the superclass save method for approved objects, they never actually get saved to the database.

Django admin model save - Update existing object

This seems really simple.
On my model save() I want to basically do a get_or_create(). So I want to update the model if it exists or create a new one if not.
This seems like a super simple problem, but I am not getting it right!
class StockLevel(models.Model):
stock_item = models.ForeignKey(StockItem)
current_stock_level = models.IntegerField(blank=True, default=0)
def save(self):
try:
# it exists
a = StockLevel.objects.get(stock_item=self.stock_item)
a.current_stock_level = self.current_stock_level
a.save()
except:
# is does not exist yet
# save as normaly would.
super(StockLevel, self).save()
OR
def save(self):
stock_level_item , created = StockLevel.objects.get_or_create(stock_item=self.stock_item)
stock_level_item.current_stock_level = self.current_stock_level
stock_level_item.save()
This would also go into a infinite loop.
This would just put the save() in an infinite loop. But that is the basic idea of how it should work.
Django uses the same save() method for both creating and updating the object.
User code doesn't need to determine whether to create or update the object, since this is done by the method itself.
Furthermore you can force the save() method to create or update the object by using the methods optional arguments.
This is covered in the Django docs.
This really doesn't sound like the best way to do this. The save method is meant for saving the current instance, not magically querying for an existing one. You should take care of this in the form or view code.
So this is how i solved a similar situation just yesterday,
I created a duplicate model to store the updated information.
let's call the new model "StockLevelUpdates".
I then used signals to insert the saved data from the original model.
I will use your model above as the original model to explain further.
class StockLevelUpdates(models.Model):
stock_item = models.ForeignKey(StockItem)
current_stock_level = models.IntegerField(blank=True, default=0)
#receiver(signals.post_save, sender=StockLevel)
def update_info(sender, instance, **kwargs):
try:
# if it exists
a = StockLevelUpdates.objects.get(stock_item=instance.stock_item)
a.current_stock_level = instance.current_stock_level
a.save()
except:
# if it does not exist yet
# save the new instance
obj = StockLevelUpdates(stock_item=instance.stock_item,
current_stock_level = instance.current_stock_level)
obj.save()
This worked well for me, and you can get all your update reports from the duplicate model.
Perhaps there is a better way to do this kind of thing but this was a quick way out of a sticky situation.

Django: making a custom PK auto-increment?

I've been using custom primary keys for a model in Django. (This was because I was importing values into the database and they already had ID's attached, and it made sense to preserve the existing values.)
class Transaction(models.Model):
id = models.IntegerField(primary_key=True)
transaction_type = models.IntegerField(choices=TRANSACTION_TYPES)
date_added = models.DateTimeField(auto_now_add=True)
However, now I want to add new instances of the model to the database, and I'd like to autogenerate a unique primary key. But if I don't specify the ID at the time of creating the instance, I get an error:
t = Transaction(transaction_type=0)
t.save()
gives:
IntegrityError at /page
(1048, "Column 'id' cannot be null")
How can I autogenerate a unique ID to specify for new values, without having to alter the way I import the existing values?
UPDATE
I've written this custom method, which seems to work...
class Transaction(models.Model):
def save(self, *args, **kwargs):
if not self.id:
i = Transaction.objects.all().order_by('-id')[0]
self.id = i.id+1
super(Transaction, self).save(*args, **kwargs)
You can use AutoField for the column id instead of IntegerField. The following should work for you:
id = models.AutoField(primary_key=True)
id will now increase automatically and won't have concurrency problems as it may encounter in save method.
I've ended up using very similar piece of code, but have made it slightly more generic:
def save(self, *args, **kwargs):
if self.id is None:
self.id = self.__class__.objects.all().order_by("-id")[0].id + 1
super(self.__class__, self).save(*args, **kwargs)
it uses self.__class__ so you can just copy paste this code to any model class without changing anything.
How are you importing the existing values? It would be trivial to write something into your Transactions __init__ to generate a new ID for you, but without knowing how you're importing the other values I can't say for sure whether it will alter the way you work with them.
If you remove your declared id field, django will automatically assume this:
id = models.AutoField(primary_key=True)
In Django 1.8, inspectdb will automatically detect auto_increment and use an AutoField when generating models.
Django migrations will do most of the hard work for you here.
Firstly, stop any access to your app so users can't change the database whilst you are working on it.
It would then be very wise to backup your database, before performing any work, as a precaution.
Remove your manually declared id field from your models.py (i.e. delete it).
Run makemigrations and then migrate. Django will modify the id field to the correct implementation for your database version.
Run this (example) command in psql adapting, if need be, to your table names:
select setval(pg_get_serial_sequence('transactions_transaction', 'id'), max(id)) from transactions_transaction;
This will set your id field to the correct serial sequence value in postgres for your table (i.e. the largest value of the id field of your existing records). This is crucial, as otherwise the value will be 1!
And that's it: from now on everything will be automatic again.