Mitchell van Zuylen
Mitchell van Zuylen

Reputation: 4125

Django. Creating a field that is a copy of an existing field in a related model.

I would like to have a field, that is simply a copy of another field.

Class Foo(models.Model):
    bool = models.BooleanField(default=False)

class Bar(models.Model):
    foo = models.ForeignKey(Foo, related_name='bar')
    copy = foo.bool # i would want this to be equal to bar.foo.bool

Upvotes: 1

Views: 65

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599600

I think you are looking for a property:

class Bar(models.Model):
    foo = models.ForeignKey(Foo, related_name='bar')

    @property
    def copy(self):
        return self.foo.bool

Note, even for your real use case this is pretty pointless, you can always access the image field via the FK.

Upvotes: 1

Rarblack
Rarblack

Reputation: 4664

You cannot do this in this in models, even if possible it is not advised. Further, you can use django.db.models.signals.post_save signals to store the same results when a field or model gets saved or updated. Another way is changing values in views.py.

Upvotes: 0

Related Questions