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

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

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=&#39;avatar.jpg&#39;, blank=False, null=False, upload_to =&#39;profile_images&#39;, 

)


#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 &gt; 200 or img.width &gt; 150:
        output_size = (150, 250)
        img.thumbnail(output_size)
        img.save(self.image.path)
        



def __str__(self):
    return f&#39;{self.customer.username}-Profile&#39;

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&#39; {self.customer} - Account No: {self.account_number}&#39;

Here is my Views:

def create_account(request): 
#Search Customer
    if searchForm.is_valid():
        #Value of search form
        value = searchForm.cleaned_data[&#39;value&#39;]
        #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 = {
    
        &#39;customers&#39;:paged_list_customers,
       
    }
    return render(request, &#39;dashboard/customers.html&#39;, context)

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

{% for customer in customers %} 


              &lt;tr&gt;
                &lt;td&gt;{{ forloop.counter }}&lt;/td&gt;
                &lt;td&gt;{{ customer.account_number  }}&lt;/td&gt; 

                {% if customer.customer.profile.surname == None %}

                &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;

                {% else %}
                
                &lt;td&gt;{{ customer.customer.profile.surname }} {{ customer.customer.profile.othernames }}&lt;/td&gt;
                
                &lt;td&gt;{{ customer.customer.profile.phone }}&lt;/td&gt;

                &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;
                
                
                
                &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;
                


                &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;
                {% endif %}
                
                
              &lt;/tr&gt;
              {% 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(&#39;user-register&#39;)
else:
    count_users = User.objects.count() 
    #Get the Customer User&#39;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.

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:

确定