0

while trying to save an instance of a model, I can't access the attributes values in the custom save() method. I think it should be possible straight forward, just like the docs state. Here's what my code looks like:

class ModelName(models.Model):
    attribute1 = models.ManyToManyField("app.ModelName2", related_name="model_name_2")
    attribute2 = models.ForeignKey("app.ModelName3", related_name="model_name_3")

    def save(self, *args, **kwargs):
        super().save()
        print(self.attribute1.all()) # <---- it prints an empty qs, but in reality there are instances passed to attribute1 field.

Does anyone have any idea why that would happen? I'm pretty sure I'm missing something super obvious. Thanks in advance!

kczan
  • 392
  • 1
  • 3
  • 9
  • 1
    Those instances are added _after_ save is called as your model instance needs to have a pk before such related instances are added because m2ms are stored in an extra _intermediate_ database table. – Abdul Aziz Barkat Jun 04 '21 at 11:59
  • Ok, that seems like an issue here, can you tell me what would be the proper way to go if I want to for example create other models based on ModelName.attribute1 values? – kczan Jun 04 '21 at 12:01
  • Does this answer your question? [Django: accessing ManyToManyField objects after the save](https://stackoverflow.com/questions/2197747/django-accessing-manytomanyfield-objects-after-the-save) – Abdul Aziz Barkat Jun 04 '21 at 12:03
  • Unfortunately not, when using models.signals.m2m_changed in the receiver, the function isn't even being called, whereas when using models.signals.post_save, it is called 2 times and both have an empty queryset :( – kczan Jun 04 '21 at 12:14
  • UPDATE: m2m_changed needed the sender to be set like ModelName.attribute1.through, while I was trying to have it set only to ModelName. Now I can access the qs properly! Thanks for your help, can you post an answer so I can accept it? – kczan Jun 04 '21 at 12:21
  • Posting an answer would be counterintuitive to me marking it as a duplicate wouldn't it? You would have gotten some feedback about your question potentially being answered somewhere else, please accept that. :) – Abdul Aziz Barkat Jun 04 '21 at 12:34
  • Ok, that seems reasonable. – kczan Jun 04 '21 at 12:51

1 Answers1

0

Which App Inside Create This Model,You Have To Install App In setting.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    '<your_app_name>'
]
AUTH_USER_MODEL = '<app_name>.<model_name>

'