最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Save all objects in QuerySet and related objects to a fixture - Stack Overflow

programmeradmin0浏览0评论

I've written a function to save a QuerySet to a fixture JSON file:

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)

But it doesn't save related objects.

I would like it to also save the objects that reference one of the objects of the QuerySet via a ForeignKey, OneToOneField, etc. How can I do that?

发布评论

评论列表(0)

  1. 暂无评论