一、models.py
1. 编写 AddressManager 类来继承 models.Manager
2. 添加 get_default_address(self, user) 方法查询数据库后将对应的数据返回
3. 在 Address 模型类中创建一个 AddressManager 管理器类的对象用于外部调用
1 from django.db import models 2 3 4 class AddressManager(models.Manager): 5 """地址模型管理器""" 6 def get_default_address(self, user): 7 """获取用户默认收货地址""" 8 try: 9 address = self.get(user=user, is_default=True) 10 except self.model.DoesNotExist: 11 address = None 12 13 return address 14 15 16 class Address(BaseModel): 17 '''地址模型类''' 18 user = models.ForeignKey('User', verbose_name='所属账户') 19 receiver = models.CharField(max_length=20, verbose_name='收件人') 20 addr = models.CharField(max_length=256, verbose_name='收件地址') 21 zip_code = models.CharField(max_length=6, null=True, verbose_name='邮政编码') 22 phone = models.CharField(max_length=11, verbose_name='联系电话') 23 is_default = models.BooleanField(default=False, verbose_name='是否默认') 24 25 objects = AddressManager() 26 27 class Meta: 28 db_table = 'df_address' 29 verbose_name = '地址' 30 verbose_name_plural = verbose_name
二、views.py
1 from django.shortcuts import render 2 from apps.user.models import Address 3 4 5 class UserAddressView(View): 6 """用户中心-地址页""" 7 def get(self, request): 8 """显示地址页""" 9 address = Address.objects.get_default_address(request.user) 10 11 return render(request, 'user_center_site.html', {'page': 'address', 'address': address})