Home > Blockchain >  Accessing self reference object in property/method Django
Accessing self reference object in property/method Django

Time:10-30

I have a user model

class Account(AbstractBaseUser):

    first_name = models.CharField(max_length = 255, unique = False)
    last_name = models.CharField(max_length = 255, unique = False)
    email = models.EmailField(verbose_name = "email", max_length = 60, unique = True)

    is_sponsor = models.BooleanField(blank=True, default=True, help_text='Check if the user is a sponsor', verbose_name='Is this user a sponsor?')
    sponsored_by = models.ForeignKey('self',blank=True,null=True, on_delete=models.SET_NULL, default=None,limit_choices_to={'is_sponsor': True}),

    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)

    USERNAME_FIELD = 'email' 

    REQUIRED_FIELDS = [
        'first_name',
        'last_name',
    ]

I have made a property for which I need to make use of 'sponsored_by'

@property
def sponsored_by_test(self):
    if self.sponsored_by is not None:
        if self.sponsored_by.first_name=="test":
            return True
    return False

When I test it,

x = Account.objects.get(first_name="test")
print(x.sponsored_by)

>>>  (<django.db.models.fields.related.ForeignKey>,)

Hence I cannot access the 'sponsored_by' variable in the property (or anywhere).

Am I missing something here?

CodePudding user response:

You need to call the property x.sponsored_by_test not x.sponsored_by.

CodePudding user response:

So simple:

In [11]: b = Account.objects.create(first_name='test2', last_name='2', email='[email protected]')

In [12]: x.sponsored_by=b

In [13]: x.save()

In [14]: print(x.sponsored_by)
123@qq.com2

for the property

@property
def sponsored_by_test(self):
    return getattr(self.sponsored_by, 'first_name', None) == "test"
  • Related