Django loaddata ignore existing objects
Asked Answered
C

1

13

I have a fixture with list of entries. eg:

[
  {
    "fields": {
      "currency": 1,
      "price": "99.99",
      "product_variant": 1
    },
    "model": "products.productprice",
    "pk": 1
  },
  {
    "fields": {
      "currency": 2,
      "price": "139.99",
      "product_variant": 1
    },
    "model": "products.productprice",
    "pk": 2
  }
]

This is only initial data for each entry (The price might change). I would like to be able to add another entry to that fixture and load it with loaddata but without updating entries that already exist in the database.

Is there any way to do that? Something like --ignorenonexistent but for existing entries.

Chavers answered 10/12, 2018 at 10:7 Comment(0)
M
1

If you keep pk in the json like that, you will always overwrite the first two records in product.productprice.

I would use "pk: null". This way, you will always create new record with every load.

So if you want to create a new price:

[
  {
    "fields": {
      "currency": 1,
      "price": "99.99",
      "product_variant": 1
    },
    "model": "products.productprice",
    "pk": 1
  },
  {
    "fields": {
      "currency": 2,
      "price": "139.99",
      "product_variant": 1
    },
    "model": "products.productprice",
    "pk": 2
  },
  {
    "fields": {
      "currency": 4,
      "price": "9.99",
      "product_variant": 1
    },
    "model": "products.productprice",
    "pk": null
  }
]

The first two records are always be the same, but if you already added a third one ( pk:3 ) with the last section you will create a new productprice with pk: 4.

BTW: if your currency field is an other primary key(with autoincrement), you can put "null" there too, a new primary key will be generated.

Matri answered 26/8, 2021 at 8:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.