Pgvector is an extention foor postgres which is useful to build vectorfield to store embedding etc.
How will we implement in our django application ?
- Install pgvector
- Create a empty migration file and add the pgvector-extension to the postgres and migrate it
- Finally add the field in any of your model
Let's get started -
1. Install pgvector
pip install pgvector
Official Repo : https://github.com/pgvector/pgvector
2. Create an empty migration file
I am assuming you have already created the app,where the vector field will be used in its models.
python manage.py makemigrations <your-app-name> --name enable_pgvector --empty
Now, when you go to your app directory you can see 0001_enable_pgvector.py newly created file inside migration folder of your app.
.
├── manage.py
├── pdf_store <<< MY APP
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ ├── 0001_enable_pgvector.py <<< HERE
│ │ ├── 0002_initial.py
│ │ └──__init__.py
│ ├── models.py
│ ├── templates
│ ├── tests.py
│ └── views.py
├── pdf_chat_project <<< MY PROJECT
│ ├── asgi.py
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── README.md
└── requirements.txt
Add the following code into it
from django.db import migrations
from pgvector.django import VectorExtension
class Migration(migrations.Migration):
dependencies = [
# Add your app's previous migration here if any
# For now if you are doing it first-time without previous migration then no need to worry !
# Just keep it blank
]
operations = [
VectorExtension(),
]
Then do migration :
python3 manage.py makemigrations
and
python3 manage.py migrate
3. Import and Add model to your models.py
Here is my code
from django.db import models
from pgvector.django import VectorField
class PDFDocument(models.Model):
title = models.CharField(max_length=255)
pdf_file = models.FileField(upload_to='pdfs/')
embedding = VectorField(dimensions=1536) # Adjust dimensions based on your model
def __str__(self):
return self.title
Then do the migration ++
Ta Da !!!
Top comments (0)