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

wbrvyc0a  于 2023-02-07  发布在  Python
关注(0)|答案(1)|浏览(164)

我正在做一个Django项目,我想得到一个属性为OneToOne的Related模型的ID,这样我就可以用相关的Profile编辑用户的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', 

)

#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}'

以下是我的看法:

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)

下面是我如何显示帐户列表中我的模板:

{% 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 %}

这是我遇到问题的客户更新视图:

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)

请理解,我想得到一个用户的ID,并与他的个人资料记录中的一个匹配,这样我就可以编辑他的个人资料记录。还请注意,客户资料是自动创建的用户注册后使用的信号。谢谢期待您的亲切回答。

dgsult0t

dgsult0t1#

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

try:
    customer_user = User.objects.get(id=pk)
except User.DoesNotExist:
    ...
else:
    ...
    user_profile = customer_user.profile

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

相关问题