K
K
Kirill Gorelov2019-06-20 16:54:22
Django
Kirill Gorelov, 2019-06-20 16:54:22

Django models, am I confused?

Guys, hello.
I create a model:

class UserSettings(models.Model):
    uid = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Пользователь")
    apikey = models.CharField(max_length=255,verbose_name="api ключ пользователя")
    ...
    
    def __str__(self):
        return self.uid

    class Meta:
        verbose_name = "Настройки пользователей"
        verbose_name_plural = "Настройки пользователя"

With such a model, if I create an entry through the admin panel, it gives me an error:
spoiler

5d0b8f3836ba6682785750.png

If I change
def __str__(self):
        return self.uid

on the
def __str__(self):
        return self.apikey

The admin panel works fine, but when I make a request
UserSettings.objects.get(uid=uid)
, it returns the apikey value to me, and I need to return everything that is stored in the database ((

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2019-06-20
@Kirill-Gorelov

First, it UserSettings.objects.get(uid=uid)returns an object of class UserSettings. You can get data from any of its attributes:

user_settings = UserSettings.objects.get(uid=uid)
print(user_settings.apikey)
print(user_settings.uid.username)

Second, the method __str__must return a string representation of the object, and the relation OneToOne is not a string.

E
Egor Kazantsev, 2019-06-21
@saintbyte

__str__ is a magic method called when an instance of a class is "wanted" as a string.
UserSettings.objects.get(uid=uid) - returns an instance of the UserSettings class, and if you try to do it with print(), the result of calling the __str__ method will be printed because print only prints lines.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question