I am getting empty in return (from my model methods), I don't get where I am wrong in this, we can query model using self
class SocialLinks(models.Model):
alias_name = models.CharField(max_length=10,)
name = models.CharField(max_length=30)
url_link = models.URLField()
def get_fb_link(self):
try:
fb = self.objects.get(alias_name='fb')
return fb.url_link
except:
return ""
def get_linkdin_link(self):
try:
linkdin = self.objects.get(alias_name='linkedin')
return linkdin
except:
return ""
def get_insta_link(self):
try:
insta = self.objects.get(alias_name='insta')
return insta.url_link
except:
CodePudding user response:
Your issue is that self
corresponds to one instance of the model class, not the class itself.
So you can do
all_fb_links = SocialLinks.objects.filter(alias_name="fb")
and you will get all the records from the model that are facebook links, but you cannot do this referencing a single instance of the record using self
.
You could write a class method, but what you actually want here is a model manager to define some specific queries so that you can then do
SocialLinks.get_all_fb_links()
Here's the docs on defining a custom manager: https://docs.djangoproject.com/en/3.2/topics/db/managers/
A method on the class like you are defining would be used to return something not stored on the table, but which could perhaps be derived from it. A simple example might be:
def link_type_and_url(self):
return f"{self.alias_name}:{url_link}"