开发者

Multiple Tables & Modified Querysets

I've got to keep an inventory of servers and their memory modules & drives. I've created three tables. I want to be able to retrieve all information about the server, including memory and drive information, and display it in one page.

class Server(models.Model):
        Name = models.CharField(max_length=25)
        ServiceTag = models.CharField(primary_key=True,max_length=12) #Uniquely identifies each server

        def __unicode__(self):
            return u'%s %s ' % (self.Name, self.ServiceTag)

class MemoryModule(models.Model):
        Manufacturer = models.CharField(max_length=15)
        Size = models.CharField(max_length=15)
        server = models.ForeignKey(Server, max_length=12)
        mems = MemoryManager()

        def __unicode__(self):
                return u'%s %s' % 开发者_如何转开发(self.Manufacturer, self.Size)

class Drive(models.Model):
        Manufacturer = models.CharField(max_length=15)
        Size = models.CharField(max_length=15)
        server = models.ForeignKey(Server, max_length=12)
        drvs = DriveManager()

        def __unicode__(self):
                return u'%s %s %s %s %s' % (self.Manufacturer, self.Size)

I was considering adding the following "managers":

class MemoryManager(models.Manager):
    def get_query_set(self):
        return super(MemoryManager, self).get_query_set().filter(server='CC98361')

class DriveManager(models.Manager):
    def get_query_set(self):
       return super(DriveManager, self).get_query_set().filter(server='CC98361')

...so that the following would generate memorymodules & drives associated with the service tag value:

MemoryModule.mems.all()
Drive.drvs.all()

a. Is this an accurate approach b. if so, how would I display "MemoryModule.mems.all() and Drive.drvs.all() in a template?


a. This looks correct, but have you tested it? With django models, there's more overhead to see if your code runs than there would be with python. I see no obvious errors; this looks by-the-book.

b. I would try something like:

<table>
{% for mem in MemoryModule.mems.all %}
    <tr>
    <td>{{ mem.Manufacturer }}</td>
    <td>{{ mem.Size }}</td>
    <td>{{ mem.drvs }}</td>
    </tr>
{% endfor %}
</table>

EDIT

Oops! My mistake. The django template engine doesn't want anything that looks like functions. It's too developerish. At worst, it allows you to call functions, but only if they take no arguments and only if they don't look like function calls. Hence, no parentheses. That said, you still need to make MemoryModule visible, i.e. pass {"MemoryModule": models.MemoryModule} into the dictionary. Better yet would be to pass {"mems":models.MemoryModule.mems.all()} and just call {% for mem in mems %} in the template.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜