Django data model related knowledge points

How to set database foreign key

pass

models.ForeignKey("目标模型名如TestModel", on_delete=models.CASCADE, verbose_name="后台管理显示的名称")

The on_delete attribute is used to handle whether the data is deleted when the foreign key is deleted.

Attributes effect
models.CASCADE After the external link is deleted, the record will be deleted synchronously
models.PROTECT The record will not be deleted after the external link is deleted
models.SET_NULL After the external link is deleted, this field is set to empty, provided that blank=True, null=True is set in the model
models.SET_DEFAULT After the external link is deleted, this field is replaced by the default value, which must be set when the model is created

Simplify data query results

In general, external link queries return a Queryset, and then continue to obtain external link data from the Queryset. In Python, the @property decorator can be used to obtain related data.

class GoodsSKU(BaseModel):
    """商品SKU表,用于保存商品具体信息"""
    status_choices = (
        (0, "下线"),
        (1, "上线"),
    )
    type = models.ForeignKey("GoodsType",blank=True, null=True, on_delete=models.SET_NULL, verbose_name="商品种类")
    goods = models.ForeignKey("GoodsSPU",blank=True, null=True, on_delete=models.SET_NULL, verbose_name="商品SPU")
    name = models.CharField(max_length=20, verbose_name="商品名称")
    desc = models.CharField(max_length=256, verbose_name="商品简介")
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="商品价格")
    unite = models.CharField(max_length=20, verbose_name="商品单位")
    image = models.ImageField(upload_to="upload/goods", verbose_name="商品图片")
    stock = models.IntegerField(default=1, verbose_name="商品库存")
    sales = models.IntegerField(default=0, verbose_name="商品销量")
    status = models.SmallIntegerField(default=1, choices=status_choices, verbose_name="商品状态")
    
    class Meta:
        db_table = "goods_sku"
        verbose_name = "商品SKU"
        verbose_name_plural = verbose_name
        
    def __str__(self):
        return self.name
    
class Banner(BaseModel):
    priority = models.IntegerField(default=0, verbose_name="优先级")
    goodsku = models.ForeignKey("GoodsSKU", on_delete=models.CASCADE, verbose_name="商品SKU")
    
    class Meta:
        db_table = "banner"
        ordering = ["update_time", "-id"]
        verbose_name = "轮播图"
        verbose_name_plural = verbose_name
        
    def __str__(self):
        return self.goodsku.name
    
    @property
    def info(self):
        """用于返回轮播图相关信息"""
        good = self.goodsku
        return {
    
    'id':good.id, 'image':good.image.url, 'name':good.name}

The above are two models, namely the product SKU model and the home page carousel Banner model. The carousel needs to provide the image link and name of the product. You can use the @property decorator to directly return the required results. The returned results are:

{
    
    'id': 1, 'image': '/media/upload/goods/1.jpg', 'name': '美果汇红肉西柚4枚礼盒 葡萄柚柚子'}

It is convenient for us to directly pass the corresponding data into the template page in the view function.

Django.contrib.auth's own user authentication system

In the actual use of the website, functions such as user login and registration are often needed. Django has designed a common User class, which can meet the general user information needs, and can be used by directly inheriting the User class.

class User(AbstractUser):
    """用户模型类"""
    class Meta:
        # 指定数据库表为user表
        db_table = "user"
        verbose_name = "用户"
        verbose_name_plural = verbose_name

After successfully synchronizing the database, you can see the corresponding field content in the user table of the database.
insert image description here
Table Structure
You can see that the administrator authority and activation status of the user are controlled by is_staff and is_active respectively.
use

django-admin.exe createsuperuser

In the subsequent interface, enter the account password of the super user to create an administrator account, and manage all model content in the background management interface of localhost:8000/admin.

After creating the user model and super administrator, you can query the content of the created user and verify the password.

>>> from user.models import User
>>> User.objects.all()
<QuerySet [<User: admin>]>
>>> User.objects.all()[0] 
<User: admin>
>>> User.objects.all()[0].get_username
<bound method AbstractBaseUser.get_username of <User: admin>>
>>> User.objects.all()[0].get_username()
'admin'
>>> User.objects.all()[0].check_password('admin')
True
>>> User.objects.all()[0].check_password('123')   
False

All user information can be obtained through the all() method. There is only one administrator account here, so the admin account information can be directly obtained by subscripting. After successful acquisition, the user name information of the returned object can be obtained through the get_username() method, or Check the password entered by the user through the check_password() method.

>>> User.objects.filter(username='admin')      
<QuerySet [<User: admin>]>
>>> User.objects.filter(username='admin')[0] 
<User: admin>
>>> User.objects.filter(username='123')     
<QuerySet []>
>>> User.objects.get(username='admin') 
<User: admin>
>>> User.objects.get(username='a')     
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\TOM\.virtualenvs\Django\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\TOM\.virtualenvs\Django\lib\site-packages\django\db\models\query.py", line 496, in get
    raise self.model.DoesNotExist(
user.models.User.DoesNotExist: User matching query does not exist.

Under normal circumstances, when there are multiple users in the data table, the filter() function is used to perform conditional query on the database. The query condition used here is username='admin', that is, to find the account information with the user name admin. Since the returned It is a QuerSet, so you need to obtain the query object by subscripting. If you can determine that there is only one eligible object in the table, you can use the get() function to query and return the queried object directly. When the get() function cannot find the corresponding object, it will throw a DoesNotExist error, which can be obtained through exception capture.

batch operation

Django's ORM model supports batch operations through the in_bulk function

# 函数使用方法
in_bulk(id_list=None, *, field_name='pk')
# Django 示例
>>> Blog.objects.in_bulk([1, 2])
{
    
    1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>}

By default, an iterable object is passed in, and it will be searched in the id column. You can also use field_name to specify the column to be searched. The return value is a dictionary. The key value is the matching element in the incoming list, and the value value is an operable model object

Guess you like

Origin blog.csdn.net/qq_20728575/article/details/125306549