gpt4 book ai didi

python - Django 模型 : How to only access fields related to a specific user from another model

转载 作者:行者123 更新时间:2023-12-04 14:05:07 25 4
gpt4 key购买 nike

我如何只能从订单模型访问指定用户(用户模型)的地址(地址模型)。这是代码:Models.py

class User(AbstractBaseUser, PermissionsMixin):
phone_number = PhoneField(max_length=12, primary_key=True, unique=True)

class Address(models.Model):
address = models.CharField(max_length=500, blank=False,null=False,primary_key=True)
customer = models.ForeignKey((User, on_delete= models.CASCADE)

class Order(models.Model):
order = CharField(max_length=400,blank=False,null=False)
customer = models.ForeignKey(User,on_delete=models.SET_NULL, null=True)
address = models.ForeignKey(Address,on_delete=models.SET_NULL, null=True)

订单模型中的地址字段是我的问题。在 Django 管理中创建新订单时,当我选择其中一个客户时,我仍然可以选择数据库中注册的任何地址

如何限制指定用户访问地址。提前致谢

最佳答案

您不能在模型中过滤它。您将需要通过表单层来完成。

我们可以通过以下方式实现:

class MyForm(forms.ModelForm):

def __init__(self, *args, user=None, **kwargs):
super().__init__(*args, **kwargs)
self.fields['address']<strong>.queryset</strong> = Address.objects.filter(<strong>user=user</strong>)

class Meta:
model = Order
fields = ['address']

然后在 View 中,我们可以构造一个以登录用户为用户的表单:

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
if request.method == 'POST':
form = MyForm(request.POST, user=request.user)
if form.is_valid():
form.instance.user = request.user
# set the order number to the instance
form.save()
return redirect('<em>name-of-some-view</em>')
else:
form = MyForm(user=request.user)
return render(request, '<em>name-of-some-template.html</em>', {'form': form})

关于python - Django 模型 : How to only access fields related to a specific user from another model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68815730/

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