杰瑞科技汇

Python IntegerField 如何正确使用与设置?

Of course! In Python, the term "IntegerField" most commonly refers to a field used in an Object-Relational Mapper (ORM), specifically the Django ORM. It's a way to define a database column that will store an integer.

Python IntegerField 如何正确使用与设置?-图1
(图片来源网络,侵删)

Let's break it down into two parts:

  1. The IntegerField in Django (The most common meaning)
  2. Python's built-in int type (The fundamental data type)

IntegerField in Django (The ORM Context)

In Django, an IntegerField is a field type you use in your models to represent an integer value in your database. It maps to an INT column in most SQL databases (like MySQL, PostgreSQL, SQLite).

Key Characteristics

  • Purpose: To store whole numbers (positive, negative, or zero).
  • Database Mapping: Typically maps to a database INTEGER or INT type.
  • Validation: Django will automatically validate that the value provided is an integer. If you try to save a string like "hello", it will raise a ValidationError.

Basic Usage

Here’s how you define a simple model with an IntegerField.

# myapp/models.py
from django.db import models
class Product(models.Model):
    name = models.CharField(max_length=200)
    # Use IntegerField to store the stock quantity
    stock_quantity = models.IntegerField()
    # Use IntegerField to store the number of times a product was viewed
    views = models.IntegerField(default=0) # 'default' provides a value if none is given
    def __str__(self):
        return self.name

Common Arguments and Options

You can customize the behavior of an IntegerField with several arguments:

Python IntegerField 如何正确使用与设置?-图2
(图片来源网络,侵删)
  • null: If True, the database will allow NULL values for this field. Default is False.

    # Optional stock quantity (can be NULL in the database)
    stock_quantity = models.IntegerField(null=True)
  • blank: If True, the field is allowed to be blank in forms. This is different from null. blank is for form validation, null is for database storage. Default is False.

    # The field can be left empty in a form
    stock_quantity = models.IntegerField(blank=True)
  • default: A default value for the field if no value is provided.

    # Default to 0 if no views are specified
    views = models.IntegerField(default=0)
  • db_index: If True, a database index will be created for this field, which can speed up queries filtering on this column.

    Python IntegerField 如何正确使用与设置?-图3
    (图片来源网络,侵删)
    # Create a database index on the 'price' column for faster lookups
    price = models.IntegerField(db_index=True)
  • unique: If True, this field must be unique throughout the entire table.

    # A unique product ID
    product_id = models.IntegerField(unique=True)
  • validators: A list of validation functions to run on the field's value.

    from django.core.validators import MinValueValidator, MaxValueValidator
    # Price must be between 0 and 10000
    price = models.IntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(10000)]
    )

Example in Practice

# Create a product instance
p = Product(name="Super Widget", stock_quantity=150)
p.save() # Saves to the database
# Access the field
print(p.stock_quantity) # Output: 150
# You can also perform queries
# Find all products with more than 100 units in stock
high_stock_products = Product.objects.filter(stock_quantity__gt=100)
# The __gt is a "lookup" for "greater than"
# This will raise a ValidationError if you try to save a non-integer
try:
    p.stock_quantity = "one hundred"
    p.full_clean() # Manually run validation before saving
    p.save()
except ValueError as e:
    print(f"Validation Error: {e}")

Python's Built-in int Type (The Fundamental Data Type)

While Django's IntegerField is for database interaction, the fundamental data type for integers in Python is the int. You use this directly in your Python code for calculations, comparisons, and general programming.

Key Characteristics

  • Purpose: To represent whole numbers.
  • Type: int is a built-in Python data type.
  • Size: In Python 3, int can be of arbitrary precision, meaning it can grow as large as your memory allows. It doesn't overflow like in some other languages (e.g., C++ or Java).

Basic Usage

# Creating integer variables
age = 30
temperature = -10
population = 8000000000
# Type checking
print(type(age)) # Output: <class 'int'>
# Basic arithmetic
sum = age + 10
difference = age - 5
product = age * 3
quotient = age / 2 # Note: This results in a float (15.0)
# Integer division (returns an int)
integer_division = age // 2 # Output: 15
# Modulo (remainder of division)
remainder = age % 3 # Output: 0
# Comparisons
print(age > 20)  # Output: True
print(age == 30) # Output: True

Relationship Between int and IntegerField

The relationship is one of mapping.

  1. When you define a model with an IntegerField, you are telling Django: "In the database, I want a column for integers."
  2. When you retrieve an object from the database, Django reads the integer value from the INT column and creates a Python int object to store it in your model instance.
  3. When you save a model instance, Django takes the Python int value from your object and converts it to the appropriate format to save into the database's INT column.

So, you work with int in your Python code, and Django handles the translation to and from the database's IntegerField.


Summary Table: IntegerField vs. int

Feature IntegerField (Django) int (Python)
Purpose Define a database column in a Django model. Represent a whole number in Python code.
Context Database modeling and ORM. General programming, calculations, logic.
Type A Django field class. A built-in Python data type.
Example models.IntegerField() my_var = 123
Key Use Storing data persistently, defining schema. Performing math, indexing, counting.
分享:
扫描分享到社交APP
上一篇
下一篇