如何从相关的Django模型中获取字段ID

huangapple go评论94阅读模式
英文:

How can I get a Field Id from a Related Django Model

问题

我正在处理一个Django项目,在这个项目中,我想要获取一个OneToOne关联模型的ID,以便我可以编辑用户的个人资料,使用相关联的Profile,但是我得到的结果是字段'id'预期是一个数字,但得到了'GANDE1'

这是我的模型:

  1. class Profile(models.Model):
  2. customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
  3. surname = models.CharField(max_length=20, null=True)
  4. othernames = models.CharField(max_length=40, null=True)
  5. gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
  6. address = models.CharField(max_length=200, null=True)
  7. phone = models.CharField(max_length=11, null=True)
  8. image = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to='profile_images')
  9. def save(self, *args, **kwargs):
  10. super().save(*args, **kwargs)
  11. img = Image.open(self.image.path)
  12. if img.height > 200 or img.width > 150:
  13. output_size = (150, 250)
  14. img.thumbnail(output_size)
  15. img.save(self.image.path)
  16. def __str__(self):
  17. return f'{self.customer.username}-Profile'
  18. class Account(models.Model):
  19. customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
  20. account_number = models.CharField(max_length=10, null=True)
  21. date = models.DateTimeField(auto_now_add=True, null=True)
  22. def __str__(self):
  23. return f'{self.customer} - Account No: {self.account_number}'

这是我的视图:

  1. def create_account(request):
  2. # 搜索客户
  3. if searchForm.is_valid():
  4. value = searchForm.cleaned_data['value']
  5. user_filter = Q(customer__exact=value) | Q(account_number__exact=value)
  6. list_customers = Account.objects.filter(user_filter)
  7. else:
  8. list_customers = Account.objects.all()
  9. context = {
  10. 'customers': paged_list_customers,
  11. }
  12. return render(request, 'dashboard/customers.html', context)

这是我在模板中显示账户列表的方式:

  1. {% for customer in customers %}
  2. <tr>
  3. <td>{{ forloop.counter }}</td>
  4. <td>{{ customer.account_number }}</td>
  5. {% if customer.customer.profile.surname == None %}
  6. <td><a class="btn btn-danger" href="{% url 'update-customer' customer.customer.id %}">Click to Enter Customer Personal Details.</a></td>
  7. {% else %}
  8. <td>{{ customer.customer.profile.surname }} {{ customer.customer.profile.othernames }}</td>
  9. <td>{{ customer.customer.profile.phone }}</td>
  10. <td><a class="btn btn-success btn-sm" href="{% url 'account-statement' customer.id %}">Statement</a></td>
  11. <td><a class="btn btn-danger btn-sm" href="{% url 'dashboard-withdrawal' customer.id %}">Withdraw</a></td>
  12. <th scope="row"><a class="btn btn-success btn-sm" href="{% url 'create-deposit' customer.id %}">Deposit</a></th>
  13. {% endif %}
  14. </tr>
  15. {% endfor %}

这是我在“客户更新”视图中遇到问题的地方:

  1. def update_customer_profile(request, pk):
  2. user = request.user
  3. try:
  4. customer_user = User.objects.get(id=pk)
  5. except User.DoesNotExist:
  6. return redirect('user-register')
  7. else:
  8. count_users = User.objects.count()
  9. user_profile = Profile.objects.get(customer=customer_user.username)

请理解,我想要获取用户的ID,并与其个人资料记录中的ID进行匹配,以便能够编辑其个人资料记录。同时请注意,客户资料是在用户注册时通过信号自动创建的。

英文:

I am working on a Django project where and I want to get an ID of a Related model with a OneToOne attributed so I can edit the profile of the user with his related Profile but all I get in return is Field 'id' expected a number but got 'GANDE1'.

Here are my Models:

  1. class Profile(models.Model):
  2. customer = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
  3. surname = models.CharField(max_length=20, null=True)
  4. othernames = models.CharField(max_length=40, null=True)
  5. gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
  6. address = models.CharField(max_length=200, null=True)
  7. phone = models.CharField(max_length=11, null=True)
  8. image = models.ImageField(default=&#39;avatar.jpg&#39;, blank=False, null=False, upload_to =&#39;profile_images&#39;,
  9. )
  10. #Method to save Image
  11. def save(self, *args, **kwargs):
  12. super().save(*args, **kwargs)
  13. img = Image.open(self.image.path)
  14. #Check for Image Height and Width then resize it then save
  15. if img.height &gt; 200 or img.width &gt; 150:
  16. output_size = (150, 250)
  17. img.thumbnail(output_size)
  18. img.save(self.image.path)
  19. def __str__(self):
  20. return f&#39;{self.customer.username}-Profile&#39;
  21. class Account(models.Model):
  22. customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
  23. account_number = models.CharField(max_length=10, null=True)
  24. date = models.DateTimeField(auto_now_add=True, null=True)
  25. def __str__(self):
  26. return f&#39; {self.customer} - Account No: {self.account_number}&#39;

Here is my Views:

  1. def create_account(request):
  2. #Search Customer
  3. if searchForm.is_valid():
  4. #Value of search form
  5. value = searchForm.cleaned_data[&#39;value&#39;]
  6. #Filter Customer by Surname, Othernames , Account Number using Q Objects
  7. user_filter = Q(customer__exact = value) | Q(account_number__exact = value)
  8. #Apply the Customer Object Filter
  9. list_customers = Account.objects.filter(user_filter)
  10. else:
  11. list_customers = Account.objects.all()
  12. context = {
  13. &#39;customers&#39;:paged_list_customers,
  14. }
  15. return render(request, &#39;dashboard/customers.html&#39;, context)

Here is how I displayed list of accounts in my Template:

  1. {% for customer in customers %}
  2. &lt;tr&gt;
  3. &lt;td&gt;{{ forloop.counter }}&lt;/td&gt;
  4. &lt;td&gt;{{ customer.account_number }}&lt;/td&gt;
  5. {% if customer.customer.profile.surname == None %}
  6. &lt;td&gt; &lt;a class=&quot;btn btn-danger&quot; href=&quot; {% url &#39;update-customer&#39; customer.customer.id %} &quot;&gt;Click to Enter Customer Personal Details.&lt;/a&gt; &lt;/td&gt;
  7. {% else %}
  8. &lt;td&gt;{{ customer.customer.profile.surname }} {{ customer.customer.profile.othernames }}&lt;/td&gt;
  9. &lt;td&gt;{{ customer.customer.profile.phone }}&lt;/td&gt;
  10. &lt;td&gt;&lt;a class=&quot;btn btn-success btn-sm&quot; href=&quot;{% url &#39;account-statement&#39; customer.id %}&quot;&gt;Statement&lt;/a&gt;&lt;/td&gt;
  11. &lt;td&gt;&lt;a class=&quot;btn btn-danger btn-sm&quot; href=&quot;{% url &#39;dashboard-witdrawal&#39; customer.id %}&quot;&gt;Withdraw&lt;/a&gt;&lt;/td&gt;
  12. &lt;th scope=&quot;row&quot;&gt;&lt;a class=&quot;btn btn-success btn-sm&quot; href=&quot;{% url &#39;create-deposit&#39; customer.id %}&quot;&gt;Deposit&lt;/a&gt;&lt;/th&gt;
  13. {% endif %}
  14. &lt;/tr&gt;
  15. {% endfor %}

Here is my Customer Update View where I am having issues:

  1. def update_customer_profile(request, pk):
  2. #get logged in user
  3. user = request.user
  4. #check if logged in user is staff
  5. try:
  6. customer_user = User.objects.get(id=pk)
  7. except User.DoesNotExist:
  8. return redirect(&#39;user-register&#39;)
  9. else:
  10. count_users = User.objects.count()
  11. #Get the Customer User&#39;s Profile from the User above
  12. user_profile = Profile.objects.get(customer=customer_user.username)

Please, understand that I want to get the ID of a User and MATCH it with the one in his profile record so I can be able to edit his profile record. And also note that the customer profile is automatically created using signals upon user registration.

答案1

得分: 0

如果您已经有了 User 对象,那么只需使用它们之间的关系:

  1. try:
  2. customer_user = User.objects.get(id=pk)
  3. except User.DoesNotExist:
  4. # 处理不存在的用户情况
  5. ...
  6. else:
  7. # 处理存在的用户情况
  8. ...
  9. user_profile = customer_user.profile

您不需要单独查询数据库。这正是关系的作用所在。

英文:

If you already have the User object, then simply use the relation between them:

  1. try:
  2. customer_user = User.objects.get(id=pk)
  3. except User.DoesNotExist:
  4. ...
  5. else:
  6. ...
  7. user_profile = customer_user.profile

You don't need to query database separately. It's exaclty what relations are for.

huangapple
  • 本文由 发表于 2023年2月7日 02:46:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365406.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定