在Django模型中投射对象 [英] Casting objects in django model

查看:60
本文介绍了在Django模型中投射对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用models.py创建具有以下代码的django项目:

I am making a django project with models.py having following code:

class Record(models.Model):
    id = models.AutoField(primary_key=True)

class TTAMRecord(Record):
    client = models.ForeignKey(TTAMClient)

class TTAMClient(models.Model):
      ...

class Account(models.Model):
     records = models.ManyToManyField(Record)
      ...

我也有以下代码将 TTAMRecord 插入到 Account records 中:

I also have following code to insert a TTAMRecord into the records of an Account:

account = Account.objects.get(...)
client = TTAMClient.objects.create(...)
record = TTAMRecord.objects.create(..., client = client, ...)
account.records.add(record)

我想做(但不能做)的是在帐户的记录对象内调用客户;例如:

What I want to do(but can't) is to call the client within the record object of an account; e.g.:

account = Account.objects.get(...)
for record in account.records.all():
      client = record.client
         ...

但是,如果不允许这样做,因为此处的 record 是存储为 Record (没有客户端)的类型,而不是TTAMRecord (具有客户端)类型...

However, if I am not allowed to do this, since record here is stored as a Record (which doesn't have client) type instead of TTAMRecord(which has client) type...

任何想法如何投射对象?我出于某些未在此处说明的目的而使用更通用的 Record 而不是 TTAMRecord ...

Any idea how to cast the object? I want to use the more generic Record instead of TTAMRecord for some purposes not stated here...

推荐答案

由于 Record 不是抽象模型,因此与其他模型一样,它具有自己的表和生命周期.但是,您可以作为 record.ttamclient 访问相应的客户端对象,因此可以将行更改为

As Record is not abstract model, it has its own table and life cycle as other models. However, you can access the corresponding client object as record.ttamclient, so you can change your line to

account = Account.objects.get(...)
for record in account.records.all():
    client = record.ttamclient
    ...

但是,如果您有多个派生类,这将很麻烦.在这种情况下,您将必须知道要引用的派生类并使用相应的属性名称.

However, this is little cumbersome if you have multiple derived classes. In such cases you would have to know which derived class you are referring to and use the corresponding attribute name.

这篇关于在Django模型中投射对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆