Property of a self instance in Django Models?

454 Views Asked by At

recently i have created a model for storing some states in my DB. It's very simple i only store id and name.

class PayType(models.Model):

    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)

    class Meta:
        ordering = ('-name',)

    def __str__(self):
        return "[{0}] {1}".format(self.id, self.name)

Here you can see a migration where i insert default values in the DB.

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('stockmanager', '0023_pagotipo_remove_carrito_unidades_totales_and_more'),
    ]

    def insertPayType(apps, schema_editor):
        PayType = apps.get_model('stockmanager', 'PayType')
        PayType(name="Credit").save()
        PayType(name="Debit").save()
        PayType(name="Cash").save()

    operations = [
        migrations.RunPython(insertPayType)
    ]

As you can see, i'll have fixed rows in DB. I'd like to add properties in the PayType Model, in order to have easy access the instances of the model. Like a static attribute in java.

class PayType(models.Model):

    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)

    class Meta:
        ordering = ('-name',)

    def __str__(self):
        return "[{0}] {1}".format(self.id, self.name)

    # I'm looking for something like this
    @property
    def CREDIT(self):
        return self.objects.get(id = 1)
    # I also tried with this, same result :(
    @property
    def DEBIT(self):
        return get_object_or_404(self, id = 2)

I tried to access in a diferent part of my code with this


class Pay(models.Model):
    id = models.AutoField(primary_key=True)
    order_id = models.IntegerField()
    value = models.FloatField()
    pay_type = models.ForeignKey(PayType, on_delete=models.CASCADE)

Pay(
    order_id = order_id,
    value = 100,
    # I want this
    pay_type = Pay.CASH #Error line
).save()

The thing is that i receive this error

Cannot assign "<property object at 0x00000138FEAC7F60>": "Pay.pay_type" must be a "PayType" instance.

Any idea?

1

There are 1 best solutions below

2
Patryk Szczepański On

Can't you just write your logic this way? It should work as indeed:

# I'm looking for something like this
    @property
    def CREDIT(self):
        return PayType.objects.get(id = 1)
    # I also tried with this, same result :(
    @property
    def DEBIT(self):
        return get_object_or_404(PayType, id = 2)

You could also try to fetch PayType class using meta framework or try to catch it using type(self), I think it should work.