模型字段如何从另一个模型字段获取数据?

时间:2022-07-26 18:48:39

I have a model in which I specify certain fields.

我有一个模型,我指定了某些字段。

class Upload_files(models.Model):
    title           =models.CharField(max_length=100, blank=True , null=True)
    image           =models.ImageField(upload_to='images')
    attributes      =models.ForeignKey(Product_attributes, blank=True , null=True)
    value           =models.CharField(max_length=100, blank=True , null=True)
    price           =models.CharField(max_length=100, blank=True , null=True)

    def __unicode__(self):
            return unicode(self.id)

Now i want to create another table which have only three fields(upload id, attribute id and value) . these fields must take the value from above table i.e., upload_id, attribute which i select above and also the value and is only readable from admin pannel.

现在我想创建另一个只有三个字段的表(upload id,attribute id和value)。这些字段必须取上面表格中的值,即upload_id,我在上面选择的属性以及值,并且只能从admin pannel中读取。

I used the following code

我使用了以下代码

class Product_values(models.Model):
    product         =models.ForeignKey(Upload_files, blank=True , null=True)
    attributes      =models.ForeignKey(Product_attributes, blank=True , null=True)
    value           =models.CharField(max_length=100, blank=True , null=True)
    def __unicode__(self):
            return unicode(self.product)

I know does not work as i said but how can i do that,so that value and attribute field takes the value by default as i define it in upload_files model.

我知道不能像我说的那样工作,但我怎么能这样做,所以当我在upload_files模型中定义它时,值和属性字段默认采用该值。

EDIT

I simply wants that when i insert the values in upload_files model from admin pannel , a instance of uploaded file is created in another table with upload id , attribute and value which i define earlier

我只是想在我从admin pannel插入upload_files模型中的值时,在另一个表中创建上传文件的实例,其中包含我之前定义的上传ID,属性和值

1 个解决方案

#1


1  

Use the post_save signal, and write and connect a receiver function that creates the Product_values entry like that:

使用post_save信号,编写并连接创建Product_values条目的接收函数,如下所示:

def create_product_entry(sender, instance, created, **kwargs):
    # enter your code here

post_save.connect(create_product_entry, sender=Upload_files)

#1


1  

Use the post_save signal, and write and connect a receiver function that creates the Product_values entry like that:

使用post_save信号,编写并连接创建Product_values条目的接收函数,如下所示:

def create_product_entry(sender, instance, created, **kwargs):
    # enter your code here

post_save.connect(create_product_entry, sender=Upload_files)