数据库配置

# Database

# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.sqlite3',

        'NAME': BASE_DIR / 'db.sqlite3',

    }

}

 

models.py里面

一张表对应一个class

 

定义好class之后,python  manage.pt makemigrations,生成迁移文件

faqs\migrations\0001.sql

 

然后执行迁移操作python manage.py migrate

 

可以用sqlite studio软件,来打开sqlite3数据库。

 

 

后期处理数据,用ORM模型

 

how to use model.CharField, explain the parameters

In Django, CharField is a field that allows you to store strings with a maximum length. The CharField class inherits from the Field class and has several optional parameters:

max_length (required): The maximum length of the field's value.

blank (optional): If True, the field is allowed to be blank (null or empty).

null (optional): If True, the field is allowed to be null (None).

default (optional): The default value for the field.

choices (optional): A sequence of 2-tuples that defines the valid choices for the field.

verbose_name (optional): A human-readable name for the field.

help_text (optional): Additional help text for the field.

validators (optional): A list of validator functions to run on the field's value.

error_messages (optional): A dictionary of error messages to use for validation errors on this field.

Here's an example of how to use CharField to define a model field:

from django.db import models

class MyModel(models.Model):

my_field = models.CharField(max_length=50, blank=True, null=True, default='default value')

In this example, my_field is a CharField with a maximum length of 50. It's allowed to be blank or null, and has a default value of 'default value'.

 

autofield vs bigautofield

In Django models, AutoField and BigAutoField are both used to define an auto-incrementing primary key for a model. However, they differ in the maximum value they can store.

AutoField is an integer field that automatically increments the value of the field for each new object created. It can hold up to a maximum value of 2,147,483,647 (2^31-1). This field is suitable for small to medium-sized applications.

BigAutoField is a larger integer field that can hold up to a maximum value of 9,223,372,036,854,775,807 (2^63-1). This field is suitable for large-scale applications that need to handle a lot of data and have a large number of objects.

In general, it's recommended to use AutoField unless you have a specific need for the larger size of BigAutoField. Using a larger field than necessary can lead to increased database storage requirements and slower query times.

 

null vs blank

In Django models, null and blank are parameters that can be set for a field.

null=True specifies that the field can be set to NULL in the database. This means that the field can have no value. By default, null is False.

blank=True specifies that the field is allowed to be blank in forms. This means that the field is not required to have a value when a form is submitted. By default, blank is False.

It's important to note that null and blank are independent of each other. A field can be null but not blank, meaning that it can have no value in the database but still be required in forms. Conversely, a field can be blank but not null, meaning that it is not required in forms but must have a value in the database.

 

Python mange.py shell进入当前项目的Python环境

命令行新建model的对象,并调用save方法。

 

objects.create创建一个新对象,会直接塞到数据库

faqsdata.objects.all()

代码块结束,shift+enter两次

 

faqsdata.values() vs values_list()

values() and values_list() are two methods that allow you to retrieve data from Django models in a more structured way. Here are the differences:

values(): Returns a QuerySet that contains a dictionary of field names and their values for each object in the QuerySet. The dictionary keys are the field names and the values are the corresponding field values. You can pass arguments to values() to specify which fields to include in the dictionary. You can also use the annotate() and aggregate() methods with values() to perform calculations on the returned values.

values_list(): Returns a QuerySet that contains a tuple of field values for each object in the QuerySet. You can pass arguments to values_list() to specify which fields to include in the tuple. By default, values_list() returns the values in the order they were declared in the model.

In summary, values() returns a dictionary with field names as keys, while values_list() returns a tuple with field values in order. So, if you want to access specific fields of a model instance using the field names, you can use values(). But if you just want to get the values of specific fields in a tuple, you can use values_list().

 

filter(id__in=[2, 5]) in Django ORM will retrieve all objects from the database whose id is either 2 or 5.

Here's how it works:

filter() method is used to retrieve objects that match a certain condition from the database.

id is the primary key of the model.

__in is a lookup that matches objects with a value that is contained in a list.

[2, 5] is the list of values that we want to match against.

So, filter(id__in=[2, 5]) will return all objects whose id is either 2 or 5.

 

You can use the __range filter to get records with an id between 2 and 5 (inclusive). Here's an example:

from myapp.models import MyModel

results = MyModel.objects.filter(id__range=[2, 5])

This will return all records where the id is between 2 and 5. The __range filter is inclusive, so records with id values of 2 or 5 will be included in the results. 

 

 In the sample FaqsData.objects.filter(id__gte=2, id__lte=5), the id__gte=2 condition includes the id value of 2, and the id__lte=5 condition includes the id value of 5. So, the query will return all the FaqsData objects whose id is greater than or equal to 2 and less than or equal to 5, which includes objects with id values of 2, 3, 4, and 5.

 

 

write a function to print all data in all().iterator() using next()

Here's an example function that uses next() to iterate through a queryset returned by all().iterator() and print each row of data:

from django.apps import apps

def print_all_data(app_name, model_name):

# Get the model class

model_class = apps.get_model(app_label=app_name, model_name=model_name)

# Get an iterator for all rows of data in the table

data_iterator = model_class.objects.all().iterator()

# Loop through the iterator and print each row of data

while True:

try:

row = next(data_iterator)

print(row)

except StopIteration:

break

 

You can also use the iterator() method on the queryset object to explicitly get an iterator. This can be useful if you want to process the objects in batches to reduce memory usage. For example:

my_queryset = MyModel.objects.all().iterator()

while True:

batch = list(itertools.islice(my_queryset, 100))

if not batch:

break

# process batch of objects

In this example, the queryset is processed in batches of 100 objects at a time, which can help to reduce memory usage. The islice() method from the itertools module is used to slice the iterator into batches.

 

 

Django's QuerySet API supports a variety of operators for filtering and querying data. Some of the commonly used operators are:

__exact: case-sensitive match for exact value

__iexact: case-insensitive match for exact value

__contains: case-sensitive containment test

__icontains: case-insensitive containment test

__in: membership in a list or queryset

__gt: greater than

__gte: greater than or equal to

__lt: less than

__lte: less than or equal to

__startswith: case-sensitive test for starts with

__istartswith: case-insensitive test for starts with

__endswith: case-sensitive test for ends with

__iendswith: case-insensitive test for ends with

__range: inclusive range

__year: extract year from a date field

There are many other operators as well, you can find the complete list in the Django documentation.

 

In Django's QuerySet API, several operators and methods are supported for performing operations on querysets. These include:

| (OR operator): Combines two querysets, returning a new queryset that contains all of the items in either queryset.

& (AND operator): Combines two querysets, returning a new queryset that contains only the items that are in both querysets.

- (Difference operator): Returns a new queryset containing all items from the first queryset that are not in the second queryset.

* (Intersection operator): Returns a new queryset containing only the items that are in both querysets.

distinct(): Returns a new queryset that contains only unique items.

exclude(): Returns a new queryset that contains only items that do not match the specified condition.

filter(): Returns a new queryset that contains only items that match the specified condition.

These are the most commonly used operators and methods, but there are others as well.

 

 

 

 

 

 

 

相关文章

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。