def save_as_fixture(query_set: QuerySet, fixture_name: str, app_label: str='mainapp'):
app_config = apps.get_app_config(app_label)
fixture_dir = os.path.join(app_config.path, "fixtures")
os.makedirs(fixture_dir, exist_ok=True)
fixture_path = os.path.join(fixture_dir, fixture_name)
data = serializers.serialize("json", query_set, indent=2, use_natural_foreign_keys=True, use_natural_primary_keys=True)
with open(fixture_path, 'w') as file:
file.write(data)
但没有保存相关的对象。
我希望它也能保存通过a,ForeignKey
OneToOneField
等引用QuerySet的对象之一的对象。我该怎么做?
您的功能正确地将Queryset序列到JSON固定装置中,同时使用其自然值保留外键和主键。但是,它不会自动包含相关对象,如果您需要一个完整的数据集,这可能是一个问题。增强您的功能以包含相关对象 您需要确保固定装置中包含所有相关对象(例如,外键,多一关系)。您可以通过递归获取相关对象来做到这一点。 改进版本
import os
from django.apps import apps
from django.core import serializers
from django.db.models import QuerySet
def get_related_objects(queryset):
"""Recursively collect all related objects for the given queryset."""
collected_objects = set(queryset)
for obj in queryset:
for field in obj._meta.get_fields():
if field.is_relation and not field.auto_created:
related_objects = getattr(obj, field.name)
if related_objects is None:
continue
if field.many_to_many or field.one_to_many:
related_queryset = related_objects.all()
else:
related_queryset = [related_objects]
collected_objects.update(related_queryset)
collected_objects.update(get_related_objects(related_queryset))
return collected_objects
def save_as_fixture(queryset: QuerySet, fixture_name: str, app_label: str = 'mainapp'):
"""Save a queryset and its related objects to a JSON fixture file."""
app_config = apps.get_app_config(app_label)
fixture_dir = os.path.join(app_config.path, "fixtures")
os.makedirs(fixture_dir, exist_ok=True)
fixture_path = os.path.join(fixture_dir, fixture_name)
# Collect all related objects
full_queryset = get_related_objects(queryset)
# Serialize to JSON
data = serializers.serialize("json", full_queryset, indent=2,
use_natural_foreign_keys=True,
use_natural_primary_keys=True)
# Write to file
with open(fixture_path, 'w') as file:
file.write(data)
它如何工作 get_releated_objects(querySet):递归找到所有相关对象(外键,多一对,一对多)。 save_as_fixture(): 收集完整的数据集,包括相关对象。 将其序列化为JSON固定装置。 将其保存到指定的Django应用程序中的固定目录。 为什么这会更好 ✅自动包含所有相关对象。 ✅加载固定装置时确保完整的数据完整性。 ✅在恢复数据库时会防止缺失依赖项。
现在,当您致电时:
save_as_fixture(MyModel.objects.filter(some_condition), "my_fixture.json")
它将保存myModel实例及其所有相关对象。 🚀