英文:
How can I get a Field Id from a Related Django Model
问题
我正在处理一个Django项目,在这个项目中,我想要获取一个OneToOne关联模型的ID,以便我可以编辑用户的个人资料,使用相关联的Profile,但是我得到的结果是字段'id'预期是一个数字,但得到了'GANDE1'。
这是我的模型:
class Profile(models.Model):
    customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    surname = models.CharField(max_length=20, null=True)
    othernames = models.CharField(max_length=40, null=True)
    gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
    address = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=11, null=True)
    image = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to='profile_images')
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        img = Image.open(self.image.path)
        if img.height > 200 or img.width > 150:
            output_size = (150, 250)
            img.thumbnail(output_size)
            img.save(self.image.path)
    def __str__(self):
        return f'{self.customer.username}-Profile'
class Account(models.Model):
    customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    account_number = models.CharField(max_length=10, null=True)
    date = models.DateTimeField(auto_now_add=True, null=True)
    def __str__(self):
        return f'{self.customer} - Account No: {self.account_number}'
这是我的视图:
def create_account(request):
    # 搜索客户
    if searchForm.is_valid():
        value = searchForm.cleaned_data['value']
        user_filter = Q(customer__exact=value) | Q(account_number__exact=value)
        list_customers = Account.objects.filter(user_filter)
    else:
        list_customers = Account.objects.all()
    context = {
        'customers': paged_list_customers,
    }
    return render(request, 'dashboard/customers.html', context)
这是我在模板中显示账户列表的方式:
{% for customer in customers %}
    <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ customer.account_number }}</td>
        {% if customer.customer.profile.surname == None %}
            <td><a class="btn btn-danger" href="{% url 'update-customer' customer.customer.id %}">Click to Enter Customer Personal Details.</a></td>
        {% else %}
            <td>{{ customer.customer.profile.surname }} {{ customer.customer.profile.othernames }}</td>
            <td>{{ customer.customer.profile.phone }}</td>
            <td><a class="btn btn-success btn-sm" href="{% url 'account-statement' customer.id %}">Statement</a></td>
            <td><a class="btn btn-danger btn-sm" href="{% url 'dashboard-withdrawal' customer.id %}">Withdraw</a></td>
            <th scope="row"><a class="btn btn-success btn-sm" href="{% url 'create-deposit' customer.id %}">Deposit</a></th>
        {% endif %}
    </tr>
{% endfor %}
这是我在“客户更新”视图中遇到问题的地方:
def update_customer_profile(request, pk):
    user = request.user
    try:
        customer_user = User.objects.get(id=pk)
    except User.DoesNotExist:
        return redirect('user-register')
    else:
        count_users = User.objects.count()
        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:
class Profile(models.Model):
    customer = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
    surname = models.CharField(max_length=20, null=True)
    othernames = models.CharField(max_length=40, null=True)
    gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
    address = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=11, null=True)
image = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images', 
)
#Method to save Image
def save(self, *args, **kwargs): 
    super().save(*args, **kwargs)
    img = Image.open(self.image.path)
#Check for Image Height and Width then resize it then save
    if img.height > 200 or img.width > 150:
        output_size = (150, 250)
        img.thumbnail(output_size)
        img.save(self.image.path)
        
def __str__(self):
    return f'{self.customer.username}-Profile'
class Account(models.Model):
    customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    account_number = models.CharField(max_length=10, null=True)
    date = models.DateTimeField(auto_now_add=True, null=True) 
    def __str__(self):
        return f' {self.customer} - Account No: {self.account_number}'
Here is my Views:
def create_account(request): 
#Search Customer
    if searchForm.is_valid():
        #Value of search form
        value = searchForm.cleaned_data['value']
        #Filter Customer by Surname, Othernames , Account Number using Q Objects
        user_filter = Q(customer__exact = value) | Q(account_number__exact = value)
        #Apply the Customer Object Filter
        list_customers = Account.objects.filter(user_filter) 
    
    else:
        list_customers = Account.objects.all()
context = {
    
        'customers':paged_list_customers,
       
    }
    return render(request, 'dashboard/customers.html', context)
Here is how I displayed list of accounts in my Template:
{% for customer in customers %} 
              <tr>
                <td>{{ forloop.counter }}</td>
                <td>{{ customer.account_number  }}</td> 
                {% if customer.customer.profile.surname == None %}
                <td> <a class="btn btn-danger" href=" {% url 'update-customer' customer.customer.id %} ">Click to Enter Customer Personal Details.</a> </td>
                {% else %}
                
                <td>{{ customer.customer.profile.surname }} {{ customer.customer.profile.othernames }}</td>
                
                <td>{{ customer.customer.profile.phone }}</td>
                <td><a class="btn btn-success btn-sm" href="{% url 'account-statement' customer.id %}">Statement</a></td>
                
                
                
                <td><a class="btn btn-danger btn-sm" href="{% url 'dashboard-witdrawal' customer.id  %}">Withdraw</a></td>
                
                <th scope="row"><a class="btn btn-success btn-sm" href="{% url 'create-deposit' customer.id %}">Deposit</a></th>
                {% endif %}
                
                
              </tr>
              {% endfor %}  
Here is my Customer Update View where I am having issues:
def update_customer_profile(request, pk):
#get logged in user
user = request.user
#check if logged in user is staff
try:
    customer_user = User.objects.get(id=pk)
   
except User.DoesNotExist:
    return redirect('user-register')
else:
    count_users = User.objects.count() 
    #Get the Customer User's Profile from the User above
    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 对象,那么只需使用它们之间的关系:
try:
    customer_user = User.objects.get(id=pk)
except User.DoesNotExist:
    # 处理不存在的用户情况
    ...
else:
    # 处理存在的用户情况
    ...
    user_profile = customer_user.profile
您不需要单独查询数据库。这正是关系的作用所在。
英文:
If you already have the User object, then simply use the relation between them:
try:
    customer_user = User.objects.get(id=pk)
except User.DoesNotExist:
    ...
else:
    ...
    user_profile = customer_user.profile
You don't need to query database separately. It's exaclty what relations are for.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论