gpt4 book ai didi

python - Django 中的多对一关系

转载 作者:行者123 更新时间:2023-11-28 18:14:49 25 4
gpt4 key购买 nike

我是 django 的新手,所以这个问题。这是我的位置对象,

class Location(models.Model):
country = models.CharField(max_length=255)
city = models.CharField(max_length=255, unique=True)
latitude = models.CharField(max_length=255)
longitude = models.CharField(max_length=255)

这是我修改过的用户对象

class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True, max_length=255)
mobile = PhoneNumberField(null=True)
username = models.CharField(max_length=255, null=True)
full_name = models.CharField(max_length=255, blank=True, null=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
is_mobile_verified = models.BooleanField(default=False)
location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True)

这是用户注册 API View

class RegisterView(views.APIView):
def post(self, request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
user = serializer.save()

subject = "Please Activate Your Account!"
token = self._generate()
link = HOST + PREFIX + str(user.id) + SUFFIX + token
message = 'Please use the following link to activate your account.\n\n{}'.format(link)
from_email = settings.EMAIL_HOST_USER
to_list = [user.email, 'melissa@gmail.com']
send_mail(subject, message, from_email, to_list, fail_silently=True)

Token.objects.create(user=user, token=token)
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

这是相关的网址

url(r'^register/$', RegisterView.as_view(), name='register')

现在我想修改此端点以将位置 ID 作为路径参数,然后在我的 UserCreation 函数中添加逻辑,将用户添加到 ID 所描述的位置。有人可以帮我做这件事吗?

最佳答案

你可以这样做:

url(r'^register/(?P<location_id>[\w.-]+)/$', RegisterView.as_view(), name='regist

然后,

def post(self, request, *args, **kwargs):
self.location_id = kwargs.get('location_id', "any_default")
location = Location.objects.get(id=self.location_id)
# Now assign to user

if serializer.is_valid():
user = serializer.save()
user.location = location
user.save()

关于python - Django 中的多对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49042185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com