根据第二个模型的外键从第三个模型中获取字段

时间:2017-06-09 01:55:46

标签: python django

我有三个模型,其中一个模型来自其他每个模型以加入它们。我试图解决的问题是如何使用表2将值从表一到表三中将它们连接到序列化器中,或者如果这是我应该开始采用的方法。

模型

class ModelOne(models.Model):
    color = models.CharField()
    size = models.CharField()

class ModelTwo(models.Model):
    One_id = models.ForeignKey(ModelOne)
    Three_id = models.CharField()

class ModelThree(models.Model):

示例序列化器

class ModelThree Serializer
    model = ModelThree
    fields = ('color', 'size')

def get_color(self, obj):
    ???

def get_size(self, obj):
    ??? 

我的数据库结构

        ModelOne
-------------------------------------
id  color   size

    ModelTwo
-------------------------------------
id  ModelOneID  ModelThreeID

    ModelThree
-------------------------------------
id

2 个答案:

答案 0 :(得分:0)

我还没有得到它,但你有:模型1的列表ID对吗?

〜>你想拥有模型3(按模型2查询)

private void button5_Click(object sender, EventArgs e)
        {
            MySqlConnection cmd;
            cmd = koneksi;
            cmd.Open();
            MySqlCommand sql = new MySqlCommand("Select * from pelanggan where nama_pelanggan like %'" +textBox4.Text+"%'",cmd);
            MySqlDataAdapter ql = new MySqlDataAdapter(sql);
            DataTable tb = new DataTable();
            ql.Fill(tb);
            dataGridView1.DataSource = tb;
        }
这是吗?我不知道你想要什么...

答案 1 :(得分:0)

如果我正确理解您的问题,您有两个模型ModelOneModelThree,它们由另一个模型ModelTwo

连接
class ModelOne(models.Model):
    color = models.CharField(max_length=200)
    size = models.CharField(max_length=200)


class ModelTwo(models.Model):
    one = models.ForeignKey(ModelOne)
    three = models.ForeignKey('ModelThree')


class ModelThree(models.Model):
    some_field = models.CharField(max_length=200)

# this looks like a ManyToMany relationship between ModelThree and ModelOne
# where ModelTwo is the intermediate model 
# you may want to check the docs https://docs.djangoproject.com/en/1.11/topics/db/models/#many-to-many-relationships

并且您希望能够将ModelOne中的值查询到ModelThree。

如果您有ModelThree m3的实例,那么您可以通过查询foreignkey relation的另一面来获取所有相关的ModelOne实例:

# ex:  m3 = ModelThree.objects.first()
model_twos = m3.modeltwo_set.all()
for two in model_twos:
   print two.one.color, two.one.size