Menyediakan data awal untuk model dengan fixtures di Django

Yanwar Solahudin
Jul 28, 2017 · 2 min read

Terkadang kita perlu mempersiapkan data awal terlebih dahulu ke dalam model sebelum setting up app yang kita buat. Django menyediakan sebuah cara untuk tujuan ini yaitu dengan fixtures.


Seandainya saya memiliki model seperti:

class Product(models.Model):
sku = models.CharField(max_length=30, unique=True,
primary_key=True)
name = models.CharField(max_length=30)
base_price = models.PositiveIntegerField()
price = models.PositiveIntegerField()
stock = models.PositiveIntegerField()
stock_min = models.PositiveIntegerField()
def __str__(self):
return self.sku
class Meta:
db_table = 'product'

Untuk menyediakan data ke dalam model di atas kita memerlukan file yang berisi sekumpulan koleksi data dalam format json atau yaml.

Buat terlebih dahulu direktori bernama fixtures di dalam aplikasi. Selanjutnya buat file fixture (terserah namanya apapun) dalam dua format (silahkan sesuaikan). Di sini saya menggunakan format yaml.

sales/fixtures/products.yaml

- model: sales.Product
fields:
sku: P0001
name: Permen
base_price: 1000
price: 1300
stock: 20
stock_min: 5
- model: sales.Product
fields:
sku: P0002
name: Ciki
base_price: 1000
price: 1500
stock: 100
stock_min: 50

Cara Meload Data

Ada dua cara meload data, yang pertama adalah kita menggunakan path langsung dan kedua adalah kita bisa set nilai path-nya di dalam file settings.py. Kita coba cara pertama (sesuaikan kebutuhan). Tapi sebelum mencoba, kita membutuhkan package pyaml untuk membaca file yaml:

(envi) $ pip install pyaml

Selanjutnya load datanya:

(envi) $ python manage.py loaddata sales/fixtures/products.yaml

Resultnya:

Installed 2 object(s) from 1 fixture(s)

Kita coba lihat apakah datanya sudah ada di database:

(envi) $ python manage.py shell 

Periksa dengan kode:

>>> from sales.models import Product
>>> Product.objects.all()
<QuerySet [<Product: >, <Product: P0001>, <Product: P0002>]>

Catatan tambahan, jika kita menggunakan pk. Bentuk file yaml seperti:

- model: sales.Product
pk: 1
fields:
sku: P001
name: Permen
base_price: 1000
price: 1300
stock: 20
stock_min: 5
- model: sales.Product
pk: 2
fields:
sku: P0002
name: Ciki
base_price: 1000
price: 1500
stock: 100
stock_min: 50
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade