NewToJS
NewToJS

Reputation: 2101

Django: How to set a property in a model using @property

I'm trying to assign two properties to my User class. The first assigned property will be used in assigning the second property. Is this correct? I'm using the @property decorator...

class User(n):

    group = models.ForeignKey(Brand, null=True, blank=True)
    is_admin = models.BooleanField(default=True)

    # assign the apps property (User.apps)
    @property
    def assign_apps(self):
        self.apps = get_user_apps(self.group, self.is_admin)

    # with User.apps, assign the apps_meta property (User.apps_meta)
    @property
    def assign_apps_meta(self):
        self.apps_meta = get_user_apps_meta(self.apps)

Upvotes: 2

Views: 5198

Answers (3)

CIRCLE
CIRCLE

Reputation: 4879

I required my model to have a property that I could manipulate without it being factored into SQL queries.

Here's how I accomplished it:

class MyModel(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    description = models.CharField(max_length=255)
    value = models.DecimalField(max_digits=10, decimal_places=2)
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(auto_now=True)

    @property
    def my_property(self):
        return self._my_property

    @my_property.setter
    def my_property(self, value):
        self._my_property = value

Note that the beginning _ on self._my_property is required.

Than you can set it like:

MyModel.my_property = 123

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600059

I still don't understand why you want to use properties here. This really isn't what they are for. The property decorator is for creating getters and setters for complex attributes; that's not what you're doing at all.

This seems like a job for a simple method.

def assign_apps(self):
    self.apps = get_user_apps(self.group, self.is_admin)
    self.apps_meta = get_user_apps_meta(self.apps)

and now you can call my_user.assign_apps().

Upvotes: 3

Farrukh
Farrukh

Reputation: 98

if you're writing method that returns some value or string then you should use

@property decorator
class Person(models.Model):
    name = models.CharField(max_length=255)
    birth_date = models.DateField()

    @property
    def age(self):
        return ......

Upvotes: 0

Related Questions