(Django)在模型中定义`__str__`,其中包含尚未定义的其他模型的属性

时间:2015-12-19 02:30:24

标签: python django

对于Django 1.9,我实现了两个简单的模型:

class A(models.Model):
    def __str__(self):
        # TO IMPLEMENT: Get the name of newest model B associated with A

class B(models.Model):
    name = models.CharField(max_length=50)
    date = models.DateField()
    to_a = models.ForeignKey(A)

    def __str__(self):
        return name

模型A适用于一组模型B(通过ForeignKey to_a。)

我想让模型__str__的{​​{1}}成为A name的{​​{1}},其B与给定date相关A 1}}与to_a

例如,如果我们有两个A : [A1, A2]和三个B : [("1", 2014-01-01, A1), ("2", 2015-01-01, A2), ("3", 2015-12-19, A1)],那么A2.__str__()应该返回"3"

如何实施A.__str__

1 个答案:

答案 0 :(得分:1)

这样的事情会帮助你

$(document).ready(function() {
                $('input#photo').on('change', function() {
                    var files = !!this.files ? this.files : [];
                    if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support
                    if (/^image/.test(files[0].type)) {  // only image file
                        var reader = new FileReader();   // instance of the FileReader
                        reader.readAsDataURL(files[0]);  // read the local file
                        reader.onloadend = function() {  
                            $('div#image-preview').css('display', 'inline-block');
                            $('div#image-preview').css('background-image', 'url(' + this.result + ')'); // set image data as background of div
                            $('div#image-preview').css('width', this.width); // doesn't work??
                            $('div#image-preview').css('height', this.height); // doesn't work??
                        }
                    }
                });
            });