Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pylint Django model instance of 'str' has no member

I am using pylint-django for my Django project and one of my models is as follows:

class Registration(models.Model):
    date_added = models.DateTimeField(auto_now_add=True)
    event = models.ForeignKey(Event, on_delete=models.CASCADE)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    def __str__(self):
        first_name = self.user.first_name
        last_name = self.user.last_name
        return f'{first_name} {last_name}'

Running pylint, I am getting the following warnings:

events/models.py:61:21: E1101: Instance of 'str' has no 'first_name' member (no-member)

From the readme of pylint-django I understand this is a known issue:

"If you reference foreign-key models by their name (as string) pylint-django may not be able to find the model and will report issues because it has no idea what the underlying type of this field is."

My question is: what should I do to deal with this? I prefer not to suppress all C0111 warnings.

Thank you so much in advance for your help!

PS: I am using pylint-django as answered on Using Pylint with Django

like image 515
PythonSherpa Avatar asked Jul 13 '19 13:07

PythonSherpa


1 Answers

You can supress a warning for a certain code block:

class Registration(models.Model):
    date_added = models.DateTimeField(auto_now_add=True)
    event = models.ForeignKey(Event, on_delete=models.CASCADE)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    def __str__(self):
        # pylint: disable=E1101
        first_name = self.user.first_name
        last_name = self.user.last_name
        return f'{first_name} {last_name}'

Here you will thus only disable E1101 for that specific __str__ method. If you want to re-enable the error in the same block, you can write #pylint: enable=E1101 at the end of the block where you wish to surpress the E1101 warnings.

like image 144
Willem Van Onsem Avatar answered Oct 20 '22 00:10

Willem Van Onsem