#model methods

10 messages · Page 1 of 1 (latest)

fast sentinel
#

so i have this method in one model

def total_price(self):
    prices = []
    items: QuerySet = self.items.filter(cart=self)
    for i in items:
        prices.append(i.final_price)
    return sum(prices)

which works fine but didn't work when i made it a @property
and i can see it in admin page

in another model i have this:

class CartItem(models.Model):
    gift_amount = models.PositivSmallIntegerField(default=0)

    @property
    def gift_amount(self):
        if self.quantity >= 70:
            return 5
        ...

which uses @property but works fine
and i can see the results in admin page

but then i have this

class CustomUser(AbstractUser):
    ...
    is_sales = models.BooleanField(default=False)
    
    def sales_id(self):
        if self.is_sales:
            import secrets
            while True:
                sales_id = secrets.toke_url(5)
                if not CustomUser.objects.filter(sales_id=sales_id).exists():
                    return sales_id

which doesn't work with or without @property and errors when i try to access it from admin page or django shell

#

so anyone know why the last one doesn't work at all
and why some others only work with @property and some only work without it?

Unknown field(s) (sales_id) specified for CustomUser. Check fields/fieldsets/exclude attributes of class CustomUserAdmin.

this one of the many errors i've gotten over time

swift valve
#

At the moment that error is because you're trying to filter on sales_id in the ORM, which only accepts database fields, not properties or methods on the model: if not CustomUser.objects.filter(sales_id=sales_id).exists():

fast sentinel
swift valve
#

Presumably you'll want to store it in the database? At the moment, obj.sales_id would be different every time you call it, even for the same object.

fast sentinel
swift valve
#

Then it can't be a computed @property

#

It needs to be a proper database field, just like is_sales

fast sentinel
swift valve
#

You could override the save method to set it there, or you can provide a method to default that gets called