简体   繁体   English

Django创建新模型存储现有用户及其数据的记录

[英]Django on creating new model store records of existing user and its data

I have created a model Customer: 我创建了一个模型客户:

class Customer(models.Model):
    name = models.CharField(max_length=20, db_index=True)
    address = models.CharField(max_length=100, blank=True)
    email = models.EmailField(max_length=100, blank=True)
    users = models.ManyToManyField(User, db_index=True)
    phone = models.IntegerFeild(max_length=100, blank=True)

as well as a new model called XYZ: 以及称为XYZ的新模型:

class XYZ(models.Model):
        customer = models.OneToOneFieldOneToOneField(Customer, on_delete=models.CASCADE)
        abc = models.CharField(max_length=10, default='x')
        user = models.OneToOneField(User, on_delete=models.CASCADE)

How should I insert data into this XYZ table for an existing Customer, without using manually Insert into the query? 我应该如何在不使用手动Insert查询的情况下将数据插入现有客户的XYZ表中? Is there any Django query or way to insert the existing customer records in the XYZ table? 是否有任何Django查询或方法可将现有客户记录插入XYZ表?

Here's one way of doing it, As it is unclear how your data from XYZ is stored so I'm assuming static values. 这是一种实现方式,由于目前还不清楚如何存储来自XYZ的数据,因此我假设使用静态值。

Go into django shell. 进入django shell。 You can do this by running python manage.py shell 您可以通过运行python manage.py shell来做到这一点

Now import your models 现在导入模型

from yourapp.models import Customer, XYZ

Also import your user model 同时导入您的user模型

from django.contrib.auth.models import User

fetch the user object you want to add. 获取您要添加的用户对象。

user = User.objects.get(username='your_username')

If you want admins you can do this 如果您想要管理员,可以执行此操作

superusers = User.objects.filter(is_superuser=True) # This will get all the admins of your website. superusers = User.objects.filter(is_superuser=True) #这将获取您网站的所有管理员。 But beware this is a queryset(ie list of user objects) if there is more than one admin for your site. 但是请注意,如果您的站点有多个管理员,则这是一个查询集(即用户对象列表)。

now you can create an entry for each of the customer object into your XYZ table. 现在,您可以在XYZ表中为每个客户对象创建一个条目。

Finally, depending on your requirement you can run this loop. 最后,根据您的要求,您可以运行此循环。

for customer in Customer.objects.all():
    XYZ.objects.create(customer=customer, abc="your string", user=user)

I think what you should do is these steps: 我认为您应该执行以下步骤:

  1. python manage.py shell python manage.py shell

  2. query all Customer 查询所有客户

    from path.to.your.models import Customer 从path.to.your.models导入Customer

    customers = Customer.objects.filter(users= 客户= Customer.objects.filter(users =

  3. insert all XYZ 插入所有XYZ

    for c in customers: 对于c中的客户:

     if c.users.is_admin: xyz = XYZ( customer=c user=c.users ) xyz.save() 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM