简体   繁体   中英

How do I get clean data from foreign-key model's field in django?

I have two models

class Tennx(models.Model):
    this_a = models.CharField(max_length=100)

And

class reed(models.Model):
    ten = models.ForeignKey(Tennx)
    tennxname = #get data from this_a 

How can I get clean data from Tennx model's this_a field?

You can define a property that fetches the this_a of the related ten :

class reed(models.Model):
    ten = models.ForeignKey(Tennx, on_delete=models.CASCADE)

    @property
    def tennxname(self):
        return self.ten.this_a

you can also use this if you make a function to determine the filename with:

class reed(models.Model):
    ten = models.ForeignKey(Tennx, on_delete=models.CASCADE)
    
    def file_name_path(self, filename):
        return f'files/{self.ten.this_a}/{filename}'
    ff = models.FileField(upload_to=file_name_path, null=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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