Django 转储单个模型的数据?

发布于 2024-07-26 16:18:39 字数 329 浏览 6 评论 0原文

我可以在 Django 中仅对一个执行 dumpdata模型,而不是整个应用程序,如果是这样,怎么做?

对于应用程序来说,它是:

python manage.py dumpdata myapp

但是,我想要转储一些特定的模型,例如“myapp.mymodel”。 原因是,我在同一个应用程序中有一些巨大的、超过 300 万条记录的数据集,我不想丢弃这些数据集。

Can I perform a dumpdata in Django on just a single model, rather than the whole app, and if so, how?

For an app it would be:

python manage.py dumpdata myapp

However, I want some specific model, such as "myapp.mymodel" to be dumped. The reason being, I have some huge, 3 million records plus, datasets in the same app that I would not like dumped.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

从版本 1.1 及更高版本开始,Django dumpdata 管理命令允许您从各个表中转储数据:

./manage.py dumpdata myapp1 myapp2.my_model

您还可以在命令行上分离多个应用程序和模型。 这是规范的定义:

django-admin dumpdata [app_label[.ModelName] [app_label[.ModelName] ...]]

As of version 1.1 and greater, the Django dumpdata management command allows you to dump data from individual tables:

./manage.py dumpdata myapp1 myapp2.my_model

You can also separate multiple apps and models on the command line. Here's the canonical definition:

django-admin dumpdata [app_label[.ModelName] [app_label[.ModelName] ...]]
帅气称霸 2024-08-02 16:18:40

如前所述,您无法通过 Django 1.0 中的 manage.py 命令来执行此操作。 但是,您可以使用脚本导出 JSON 文件,并使用 loaddata 加载它:

from django.core import serializers
from myproject.myapp import models
data = serializers.serialize("json", models.MyModel.objects.all())
out = open("mymodel.json", "w")
out.write(data)
out.close()

As noted, you can't do this through a manage.py command in Django 1.0. However you could use a script to export the JSON file, and load it using loaddata:

from django.core import serializers
from myproject.myapp import models
data = serializers.serialize("json", models.MyModel.objects.all())
out = open("mymodel.json", "w")
out.write(data)
out.close()
楠木可依 2024-08-02 16:18:40

将特定模型加载到特定文件:

python manage.py dumpdata app_label.ModelName > specific_file.json

并将其加载到另一个应用程序:首先将文件移动或复制到要处理它的应用程序,然后:

python manage.py loaddata specific_file.json

A specific model to a specific file:

python manage.py dumpdata app_label.ModelName > specific_file.json

and to load it to another app: first move or copy the file to the app where you want process it, then:

python manage.py loaddata specific_file.json
找回味觉 2024-08-02 16:18:40

将 django 模型中的所有数据转换为 json 格式。

语法:

python manage.py dumpdata app_name.model_name

示例从驻留在 django 中默认身份验证应用程序中的 group_permission 模型中转储数据。

python manage.py dumpdata auth.group_permission

对于输出,请查看控制台

Take all data into json format from django model.

Syntax:

python manage.py dumpdata app_name.model_name

For example dumping data from group_permission model which reside in default auth app in django.

python manage.py dumpdata auth.group_permission

For output take a look on console.

掌心的温暖 2024-08-02 16:18:40

我认为你的问题已经有了解决方案。 您可以像这样转储单个模型:

./manage.py dumpdata myapp.my_model

I think you had the solution in your question. You can dump an individual model like this:

./manage.py dumpdata myapp.my_model
陌路终见情 2024-08-02 16:18:40

为了成功,我必须说两次,并指定模型两次,例如:

./manage.py dumpdata myapp2.my_model myapp2.my_model

如果我只说

./manage.py dumpdata myapp2 myapp2.my_model

我被 myapp2 中的所有模型淹没,尽管我指定了 my_model。

For success I had to say it twice, and specify the model two times, like:

./manage.py dumpdata myapp2.my_model myapp2.my_model

If I only said

./manage.py dumpdata myapp2 myapp2.my_model

I got flooded with all the models in myapp2, despite the fact that I specified my_model.

但可醉心 2024-08-02 16:18:40

对于像我这样的 Django 和 Python 新手来说,这可能很有用:

如果您只想转储一行(显然是单个表),并且您有应用程序“merchant”,并且模型也名为“Merchant” ”,并且您通常使用完全限定名称导入它,如下所示:merchant.models.Merchant; 甚至不要尝试使用此名称。 语法如下:

# only dumps the merchant with id = 123, pretty printed
python manage.py dumpdata merchant.Merchant --pks 123 --indent 2

For newbies in Django and Python like me, this might be useful:

if you want to only dump a single row (of, obviously, a single table) and you have for example the app "merchant" and the model is also named "Merchant", and you usually import it using a fully qualified name like this: merchant.models.Merchant; do not even try to use this name. The syntax is as follows:

# only dumps the merchant with id = 123, pretty printed
python manage.py dumpdata merchant.Merchant --pks 123 --indent 2
囚我心虐我身 2024-08-02 16:18:40

要将其写入特定文件:

python manage.py dumpdata app_label.ModelName app_label.ModelName2 > fixtures/specic.json

To write it on specific file:

python manage.py dumpdata app_label.ModelName app_label.ModelName2 > fixtures/specic.json
九歌凝 2024-08-02 16:18:40

如果只想转储模型的指定对象,可以使用 --pks dumpdata 命令的可选参数。

--pks PRIMARY_KEYS 仅输出由逗号分隔的主键列表指定的对象。 此功能仅在倾倒时可用
一个模型。 默认情况下,输出模型的所有记录。

If you want to dump only the specified objects of a model, you can use the --pks optional argument for the dumpdata command.

--pks PRIMARY_KEYS Outputs only the objects specified by a comma separated list of primary keys. This is only available when dumping
one model. By default, all the records of the model are output.

花开半夏魅人心 2024-08-02 16:18:40

我认为已接受的答案已经过时,需要在 2023 年通过详细方法进行刷新。

我遇到了类似的问题,我必须为具有特定 id 的不同应用程序的特定模型创建固定装置。 此外,我必须为所有模型创建一种夹具。 这样我们就不必加载单个灯具,而只需为所有型号加载一个灯具。

我通过创建一个自定义命令来完成所有这些操作,该命令在内部为具有特定 ID 的每个特定模型调用 dumpdata,如下所示:

products/models.py< /em>

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.DecimalField(max_digits = 5, decimal_places = 2)

reviews/models.py

class Review(models.Model):
    title = models.CharField(max_length=200)        
    text = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)
    rating = models.PositiveIntegerField(default=0)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)

    def natural_key(self):
       return self.title, self.timestamp


class Response(models.Model):
    text = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)

下面是为具有特定 id 的不同应用程序的特定模型创建一个固定装置的命令:

generate_fixture.py

from django.core.management import BaseCommand, call_command
from io import StringIO
import json

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('id', type=int, help='Primary Key Of Product')

    def handle(self, *args, **options):
        id = options.get('id')

        if product := Product.objects.filter(id=id).first():
            product_fixture = self.get_fixture('products.Product', str(id))

            review_ids = list(
                Review.objects.filter(product__id=id).values_list('id',flat=True)
            )
            review_ids = ','.join([str(review_id) for review_id in review_ids])
            review_fixture = self.get_fixture('reviews.Review', review_ids)

            output = [json.loads(product_fixture)]
            output.extend(json.loads(review_fixture))
            with open('model_fixtures.json', "w") as file:
                json.dump(output, file)
        else:
            print(f"Product with id {id} does not exists!")

    def get_fixture(self, label, pks):
        args = ['dumpdata', '--natural-foreign', '--natural-primary', label]
        with StringIO() as buffer:
            call_command(*args, pks=pks, stdout=buffer)
            data = buffer.getvalue()
        return data

现在您可以使用如下 id 运行命令:

python manage.pygenerate_fixture 50

并且模型的固定装置将在一个可以加载的固定装置文件中生成像这样:

python manage.py loaddata model_fixtures.json

I think the accepted answer is old and needs a refresher in 2023 with the detailed approach.

I had the similar problem where I had to create fixtures for specific models from different apps having specific id's. Moreover I had to create just one fixture for all models. so that we don't have to load individual fixtures rather just one fixture for all models.

I did all of this by creating a custom command that calls the dumpdata internally for each specific model with the specific ids like the following:

products/models.py

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.DecimalField(max_digits = 5, decimal_places = 2)

reviews/models.py

class Review(models.Model):
    title = models.CharField(max_length=200)        
    text = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)
    rating = models.PositiveIntegerField(default=0)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)

    def natural_key(self):
       return self.title, self.timestamp


class Response(models.Model):
    text = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)

And following is the command that creates one fixtures for specific models from different apps with specific id's:

generate_fixture.py

from django.core.management import BaseCommand, call_command
from io import StringIO
import json

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('id', type=int, help='Primary Key Of Product')

    def handle(self, *args, **options):
        id = options.get('id')

        if product := Product.objects.filter(id=id).first():
            product_fixture = self.get_fixture('products.Product', str(id))

            review_ids = list(
                Review.objects.filter(product__id=id).values_list('id',flat=True)
            )
            review_ids = ','.join([str(review_id) for review_id in review_ids])
            review_fixture = self.get_fixture('reviews.Review', review_ids)

            output = [json.loads(product_fixture)]
            output.extend(json.loads(review_fixture))
            with open('model_fixtures.json', "w") as file:
                json.dump(output, file)
        else:
            print(f"Product with id {id} does not exists!")

    def get_fixture(self, label, pks):
        args = ['dumpdata', '--natural-foreign', '--natural-primary', label]
        with StringIO() as buffer:
            call_command(*args, pks=pks, stdout=buffer)
            data = buffer.getvalue()
        return data

Now you can run the command with the id like this:

python manage.py generate_fixture 50

And fixture of the models will be generated in just one fixture file which can be loaded like this:

python manage.py loaddata model_fixtures.json

温馨耳语 2024-08-02 16:18:40

作为解决方法,您可以创建另一个应用程序并复制模型,但使用 db_table 元选项将其指向现有表。 然后您可以将复制的模型转储到新应用程序中。 您现有的应用程序不会受到影响。

As a workaround you could make another app and copy the model but point it to the existing table with the db_table meta option. Then you could just dump the models you copied into the new app. You existing app wouldn't be affected.

小清晰的声音 2024-08-02 16:18:40

我创建了一个管理命令,用于在每个模型的基础上生成一个夹具。
可以通过运行以下代码来生成夹具

./manage generate_fixtures app.model.MyModel --file=dump/MyModel.json

https://gist.github.com/2394883

I've created a management command the generate a fixture on a per model basis.
Fixtures can be generated by running:

./manage generate_fixtures app.model.MyModel --file=dump/MyModel.json

code at: https://gist.github.com/2394883

固执像三岁 2024-08-02 16:18:40

用于从特定 APP 的特定模型中 DUMPING 数据。


如果我们以主项目(我们称之为项目)为例,在这个主项目中我们有两个(02)其他应用程序(我们将每个应用程序称为 那样做


  1. 像这样的应用程序APP1APP2)我们可以像python manage.py dumpdata APP1 。 name_of_model >APP1/fixtures/name_of_model .json
  2. python manage.py dumpdata APP2.name_of_model >APP2/fixtures/name_of_model .json

For DUMPING data out of the specific model for specific APP.


If we take EXAMPLE where we have in a MAIN PROJECT (We go call it project) and in this MAIN PROJECT we have two (02) others applications (We go call each app like this APP1 and APP2) we can do like that


  1. python manage.py dumpdata APP1.name_of_model >APP1/fixtures/name_of_model .json
  2. python manage.py dumpdata APP2.name_of_model >APP2/fixtures/name_of_model .json
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文