简体   繁体   English

尝试使用 psycopg2 将数据添加到 Postgresql 数据库

[英]Trying to add data to Postgresql database using psycopg2

I was able to create the script to add data straight into Postgresql table.我能够创建脚本以将数据直接添加到 Postgresql 表中。 The only problem is ManyToManyFields.唯一的问题是ManyToManyFields。 While I'm able to add the data, I am not able to link to the ManyToMany.虽然我能够添加数据,但我无法链接到多对多。

Here is my models.py这是我的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 .我知道如果我使用Django shell ,我可以手动链接项目。 But, is there a way to add a listing and connect it with the proper category ?但是,有没有办法添加listing并将其与正确的category联系起来?

Thanks in advance.提前致谢。

You should use Django's ORM instead:您应该改用 Django 的 ORM :

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 遍历JSON数据,创建dict / list,然后使用psycopg2插入Postgresql数据库? - Iterate through JSON data, create dict/list and then insert into Postgresql database using psycopg2? psycopg2:如何将 Python 应用程序中的数据添加到 Postgresql - psycopg2: How to add data from a Python Application to Postgresql 无法使用 psycopg2 和 pythonista 应用程序访问 postgreSQL 数据库 - Unable to access postgreSQL database using psycopg2 with pythonista app 使用 python、sqlalchemy 和 psycopg2 创建 PostgreSQL 数据库时出错 - Error when creating a PostgreSQL database using python, sqlalchemy and psycopg2 使用psycopg2动态更改python中的数据库(postgresql) - change database (postgresql) in python using psycopg2 dynamically Psycopg2 - 使用连接字符串连接到 postgreSQL 数据库 - Psycopg2 - Connect to postgreSQL database using a connection string 使用psycopg2转换器从PostgreSQL检索bytea数据 - Using a psycopg2 converter to retrieve bytea data from PostgreSQL 使用psycopg2从Postgresql中基于模式的表中选择数据 - Selecting data from schema based table in Postgresql using psycopg2 使用 psycopg2 从 PostgreSQL 中基于模式的表中选择数据 - Selecting data using psycopg2 from a schema based table in PostgreSQL Postgresql&psycopg2:数据库不存在 - Postgresql & psycopg2: database does not exist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM