Trying to add data to Postgresql database using psycopg2

I was able to create the script to add data straight into Postgresql table. The only problem is ManyToManyFields. While I'm able to add the data, I am not able to link to the ManyToMany.

Here is my models.py

class Category(MPTTModel):
    name = models.CharField(max_length=150, unique=True)
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')

    class MPTTMeta:
        order_insertion_by = ['name']

    def __str__(self):
        return self.name

from django.urls import reverse

class Listing(models.Model):
    name = models.CharField('Business Name', max_length=250)
    address = models.CharField('Address', max_length=300)
    phone_number = models.CharField('Phone Number', max_length=20)
    web = models.URLField('Website')
    category = models.ManyToManyField(Category)
    main_image = models.CharField('Image Link', max_length=500)

    LISTING_STATUS = (
        ('a', 'Active'),
        ('e', 'Expired'),
        ('i', 'Inactive'),
        ('c', 'Claimed'),
    )

    status = models.CharField(
        max_length=1,
        choices=LISTING_STATUS,
        blank=True,
        default='a',
        help_text='Listing Status',
    )
    def get_cats(self):
        return ", ".join([str(p) for p in self.category.all()])
    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('listing-detail', args=[str(self.id)])

In another file, I created another code to add information into the database:

def insert(name, address, phone_number, web, status, main_image, ):
    conn = psycopg2.connect("host=localhost dbname=augustalife user=postgres")
    cur = conn.cursor()
    cur.execute("INSERT INTO listings_listing (name, address, phone_number, web, status, main_image) VALUES (%s,%s,%s,%s,%s,%s);", (name, address, phone_number, web, status, main_image))
    conn.commit()
    conn.close()

I know that I can manually link items if I am using Django shell. But, is there a way to add a listing and connect it with the proper category?

Thanks in advance.

You should use Django's ORM instead:

def insert(name, address, phone_number, web, status, main_image):
    Listing.objects.create(
        name=name,
        address=address,
        phone_number=phone_number,
        website=web,
        status=status,
        main_image=main_image,
    )

I'm not sure how you determine which categories belong to a given listing, but the process of linking a category and listing is trivial:

listing = Listing.objects.create(...)
category = Category.objects.first()
listing.categories.add(category)
Back to Top