Answer the question
In order to leave comments, you need to log in
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 = "Настройки пользователя"
def __str__(self):
return self.uid
def __str__(self):
return self.apikey
UserSettings.objects.get(uid=uid)
Answer the question
In order to leave comments, you need to log in
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)
__str__
must return a string representation of the object, and the relation OneToOne
is not a string.
__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 questionAsk a Question
731 491 924 answers to any question