我在model.py中有以下内容:
DECLARE @defaultLanguage NVARCHAR(5)
SET @defaultLanguage = (SELECT LanguageCode FROM LANGUAGE WHERE IsDefault = 1)
SELECT
c.Id,
c.Name,
c.OrgNr,
c.UserId,
c.Address,
c.PostalArea,
c.County,
c.Country,
c.Description,
c.DescriptionFull,
c.Telephone,
c.Email,
c.Website,
c.IsApproved,
s.Id,
ISNULL(tr.Name, def.Name) Name
FROM Company c
INNER JOIN CompanyService cs on cs.CompanyId = C.Id
INNER JOIN Service s on s.Id = cs.ServiceId
LEFT OUTER JOIN ServiceTranslation tr
ON s.Id = tr.ServiceId AND tr.LanguageCode = @userLanguage
-- join default language of the service:
LEFT OUTER JOIN ServiceTranslation def
ON s.Id = def.ServiceId AND def.LanguageCode = @defaultLanguage
WHERE c.IsApproved = 1
AND
c.Id IN
(
SELECT c1.Id FROM Company c1
INNER JOIN CompanyService cs1 on cs1.CompanyId = c1.Id
INNER JOIN Service s1 on s1.Id = cs1.ServiceId
INNER JOIN ServiceTranslation tr1
ON s1.Id = tr1.ServiceId AND tr1.LanguageCode = @userLanguage
-- join default language of the service:
INNER JOIN ServiceTranslation def1
ON s1.Id = def1.ServiceId AND def1.LanguageCode = @defaultLanguage
AND s1.IsApproved = 1 AND ISNULL(tr1.Name, def1.Name) LIKE '%' + @searchQuery + '%'
)
我还有一个相应的表单,在填写和汇总时,可以正确地保存到数据库中。
我不明白的是from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
university = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
ROLE = (
('CUSTOMER', 'User'), # (value to be set on model, human readable value)
('WORKER', 'Worker'),
)
role = models.CharField(max_length = 20, choices = ROLE, default = 'USER')
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
这是如何运作的?对我来说,它似乎应该是instance.profile.save()
,因为instance.Profile.save()
存在。我不确定这个小写Profile
来自何处?
答案 0 :(得分:3)
在Django中,默认情况下,反向访问者使用小写中的相关模型名称定义。
由于您的Profile
模型与one-to-one
模型之间存在User
关系,您可以访问属于User
实例的配置文件实例(例如用户)为user.profile
。
您可以使用参数覆盖此命名,您可以使用关键字参数related_name
在模型定义中定义OneToOneField。
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='myprofile')
现在,您可以通过user.myprofile
请参阅Django文档here
顺便提一下,当您通过User实例访问用户的个人资料时要小心。如果没有与Profile
实例关联的User
记录,则会引发DoesNotExist
异常。