Can anyone provide a clear example of how to show a table using django-tables2 that selects and presents data from two(or more) related models?
I've found lots of posts about that, most of them quite old, and none really a working example.
These are my models:
class Person(models.Model):
name = models.CharField(verbose_name="Name",max_length=50)
fname = models.CharField(verbose_name="F.Name",max_length=50)
class Speech(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
said = models.CharField(verbose_name="Said",max_length=50)
I simply want to show a table with columns "Name, F.Name, Said". Which is the best way? And with multiple tables?
Thanks in advance.
Well, nobody answered my question. After digging and trying I found a way to show fields from related models in one table. The thing is the table definition into tables.py should be like this:
class SpeechTable(tables.Table):
name = tables.Column(accessor='person.name')
fname = tables.Column(accessor='person.fname')
said = tables.Column()
class Meta:
attrs = {"class": "paleblue"}
Not sure if this is the best way, but it is simple and works fine.
Related
There are three tables:
users
schedules
schedules_users
The user-model and the schedules-model each have the has_and_belongs_to_many-relationship.
Now I simply want to do this:
user_id_binded = Schedule/User/Object/#I dont know!#.find_by_sql ["SELECT schedules_users.user_id FROM schedules_users WHERE schedules_users.schedule_id = ?", schedule.id]
#user_schedules_binded = User.find(user_id_binded)
BUT the return-value of the first find_by_sql must be a model, as I understood the Rails.Api correctly.
It's neither a user-model-return-value or a schedule-model-return-value.
In the schedules_users-table are all relationships between users and schedules.
So I want to get all users which are binded to a specific schedule.
First I thought this should be the right way to solve it, but at that moment I didn't know that the return-value must be a model.
How could I solve this problem?
It appears you have a schedule ID and want the users in the end - that can be done easier by join statement like #user_schedules_binded = User.joins(:schedules).where(schedules: { id: schedule_id })
Or, if you have the schedule object, schedule.users will do the same, both going through schedules_users table.
I would like to retrieve some data using one-to-many and many-to-many relations
I've created bean called floor, shop, category and related them as:
floor 1:N shop
floor N:M category
shop N:M category
Now i want to retrive all shops given category and floor ids
Here is my code
$floor = R::load('floor',$f_id);
$category = R::load('category',$cat_id);
$shops= $floor->via('category')->withCondition('id = ?',[$category ->id])->ownShopList;
var_dump($shops);
But $data is empty array. I'm shure i've related beans correctly. What am I doing wrong please help!
Maybe there is another way to retrieve them i'll appreciate any solution. Thanks!
$category = R::load('category',$cat_id);
$shops= $category->withCondition('floor_id = ?',[$f_id])
->sharedShopList;
I've figured it out finally after couple of hours was very easy and simple. so here is the solution
$category = R::load('category',$cat_id);
$shops= $category->withCondition('floor_id = ?',[$f_id])->sharedShopList;
var_dump($shops);
I'm trying to auto import data using MagicalRecord. I've read all the answers that I've found, but do not understand is it possible or not. This is how my data model looks like:
There are two steps in my app. First I'm getting organization data, and I import it using
[organization MR_importValuesForKeysWithObject:response];
This works fine, later I'm getting participants, and import them using
[participant MR_importFromArray:response];
this also works ok, only I want to also get the participant relationships added. Json that I'm getting for participants looks like this:
(
{
CoverImage = "<null>";
Id = 4377;
LogoImage = "<null>";
Name = "Participant name";
ParentOrganizationId = 2;
Phone = "123 123-1234";
}
)
ParentOrganizationId is the organizationID to which organization this participant belongs.
So the question is, when importing participants is it possible to set this relationship to already saved organizations? Maybe I need to setup relatedByAttribute or mappedKeyName in my attributes user info and that's it?
Any guidance is appreciated, thanks in advance!
Well, after 3 days of searching I've finally found it. It is possible!
This is where i found the solution to this problem.
All I had to do was
In Organization model participants relationship add mappedKeyName "Participants"
In Participant model parentOrganization relationship add mappedKeyName "ParentOrganizationId" and relatedByAttribute "organizationID".
And everything works fine using this.
I hope you can help me guys. Google unfortunately didn't helps me out and my search here at stackoverflow didn't as well :-(
I have two DomainClasses HumanResource and Task with a many-to-many relationship.
Model-Definitions:
Task:
class Tasks {
String name
static belongsTo = [HumanResource]
static hasMany = [humanResources: HumanResource]
//also tried but didn't help -> static fetchMode = [humanResources:"eager"]
}
HumanResource:
class HumanResource {
String name
static hasMany = [tasks: Tasks]
}
I also tried to add an index on the id-field with mapping={} but I also think that's not the solution, it didn't help and I think there is already an index on the id-field.
So, what I did and not works is now to find all human resources for the given tasks! And the tasks comes from Services and they are already fetched in the service model with "static fetchMode = [tasks:"eager"]"!
Controller-Code:
def listHumanResourcesFromTasks = {
def list = HumanResource.findAllByTasks(service.getTasks())
//and I tried also with an own HashMap but didn't work as well
}
I always get an error "org.springframework.dao.InvalidDataAccessResourceUsageException" with an SQL-GrammarException. But I really don't know why. The "service.getTasks()" objects are fully filled (as I wrote with fetchMode = [tasks:"eager"])...
It would be awesome if somebody could give me the winning hint.
Thanks a lot for your time.
Best wishes,
Marco
This sort of query isn't supported - you'd need to use HQL or a criteria query in general. But this particular one is easy since you have a bidirectional relationship. You can get all of the HumanResource instances for a collection of Tasks with this:
def resources = service.getTasks().collect { it.humanResources }.flatten() as Set
It needs to be a Set since the same HumanResource instance may appear multiple times so you need to condense the List into unique instances.
I know this has been asked before in several ways but none of the answers seem applicable to me - or correct - or current, so I'll try again.
I have a large model with several intstances of inherited entities. One example is a Timetable that contains a collection of TimetableEvents. There are several sub-types of TimetableEvent, such as an InterviewTimetableEvent, BreakTimetableEvent and an ExercisetimeTableEvent. ExerciseTimetableEvent has a relationship to an Exercise entity.
I need to use self-tracking entities as I'm using a WCF back end to serve up data to several WPF clients in a stateless fashion.
So, I need to eager load everything and I thought that self-tracking entities would automatically do this but it appears they dont.
So, to get a timetable I need to do something like this:
var tt = (from s in ESSDataContainer.Timetables
.Include("TimetableEvents")
where s.TimetableId == timetableid
select s).FirstOrDefault();
This will give me the TimetableEvents but not the Exercises that are related to the ExerciseTimetableEvents. Ive tried the following (and several other suggestions) without luck:
var tt = (from s in ESSDataContainer.Timetables
.Include("TimetableEvents")
.Include("ExerciseTimetableEvents.Exercise")
where s.TimetableId == timetableid
select s).FirstOrDefault();
Is there a solution to this?
If not I'll go back to normal context tracking and connect to the database from a local container rather than using WCF.
Cheers
It's a bit tricky, but possible:
var tt = (from s in ESSDataContainer.Timetables
where s.TimetableId == timetableid
select new
{
TimeTable = s,
Events = s.TimeTableEvents,
Exercise = s.TimeTableEvents.OfType<ExerciseTimetableEvents>()
.Select(ett => ett.Exercise)
}).Select(s => s.TimeTable)
.AsEnumerable()
.FirstOrDefault();
Clear as mud, but, hey: No magic strings! Also, it has the advantage that it actually works....
There is a Proposal for this issua at Microsoft Connect:. If you think this worthy you can vote for it.