N
N
neznaikaaaa2013-11-28 21:40:18
Django
neznaikaaaa, 2013-11-28 21:40:18

Join two tables into one Django

There are two tables
class modelA(models.Model):
owner = models.ForeignKey(User)
iditem = models.CharField(max_length=200)
category = models.CharField(max_length=200)
date = models.DateField()
class modelB(models .Model):
owner = models.ForeignKey(User)
iditem = models.CharField(max_length=200)
costs = models.CharField(max_length=200)
date = models.DateField()
We need to join these two tables into one, by three parameters owner, iditem, date. As a result, get the following table
class modelC(models.Model):
owner = models.ForeignKey(User)
iditem = models.CharField(max_length=200)
date = models.DateField()
costs = models.CharField(max_length=200)
category = models.CharField(max_length=200)
Also in modelB there may be iditem that are not in modelA, they must also be transferred to modelC with category=0.
Help make requests.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
tema_sun, 2013-11-28
@tema_sun

Because I can’t make such a request right away (I have to read it, and this is laziness as always), then I would do this:
- I would add the costs field to modelA
- I would get all modelB objects ( .objects.all() ). And these results would be run through "for ... in ..." creating new objects in modelA, based on the data from modelB

M
Maxim Vasiliev, 2013-11-29
@qmax

If you need to merge tables directly in the database, then you need SQL, not Django.
And if you need to make a "virtual table" at the ORM level, which would stick together a model from two others on the fly, then I would smoke on the model manager topic:
https://docs.djangoproject.com/en/1.6/topics/db/managers /
And I would write a custom manager to ModelC, which translates object.* queries into sql with joins.
In principle, it is possible to embed and save models in different tables.
Once upon a time I did this to merge three tables from three different databases (on different servers). But that was with a very ancient janga.

R
r1ch, 2013-11-29
@r1ch

you can make a view, then create a model from it
CREATE VIEW `ModelC` AS
SELECT `owner`, `iditem`, `date`, `costs`, `category` FROM `modelA`
INNER JOIN `modelB` ON `modelA`.` owner` = `modelB`.`owner` AND `modelA`.`iditem` = `modelB`.`iditem` AND `modelA`.`date` = `modelB`.`date`;
where `ModelA` is the name of the table associated with ModelA in the database
where `ModelB` is the name of the table associated with ModelB in the database

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question