1

I have a model with the following fields:

user = models.ForeignKey(User)
impact = models.IntegerField(default = value)

Where I want value to be User.get_profile().someIntField with User being the same User object that was passed to the first field. How can I do this?

Ferguzz
  • 5,777
  • 7
  • 34
  • 41

2 Answers2

3

Override save method in your model

class MyModel(models.Model):
    user = models.ForeignKey(User)
    impact = models.IntegerField()

    def save(self, *args, **kwargs):
        if not self.pk:
            self.impact = self.user.get_profile().someIntField
        super(MyModel, self).save(*args, **kwargs)
San4ez
  • 8,091
  • 4
  • 41
  • 62
2
def __init__(self, *args, **kwargs):
    super(YourModel, self).__init__(*args, **kwargs)
    self.impact = self.user.get_profile().someIntField
Ferguzz
  • 5,777
  • 7
  • 34
  • 41
John Mee
  • 50,179
  • 34
  • 152
  • 186
  • won't this completely break the way the model is initialised? don't you need to call `super(Model, self).__init__(*args, **kwargs)` ? – Ferguzz Apr 09 '12 at 10:52
  • accepted your answer after a quick read of this http://stackoverflow.com/questions/1355150/django-when-saving-how-can-you-check-if-a-field-has-changed - although I called to super for the init. – Ferguzz Apr 09 '12 at 11:18
  • cheers, I edited the super in. Feel free to make corrections - i'm not testing it whereas you probably are ;-) – John Mee Apr 09 '12 at 11:23
  • I'm tempted to edit your question to hold a more relevant subject. Like "Initialize django model capturing a derivative attribute from that moment?" or some such. Can you do that? It's not very search findable as it stands. – John Mee Apr 09 '12 at 11:27
  • 1
    Your variant means that you will hit user profile every time you create object. But as I understand Ferguzz need to get default impact value only when saving – San4ez Apr 09 '12 at 11:29