I've 4 model that has relationship through FK.
class Journal(models.Model):
name = models.CharField(max_length=255)
class Volume(models.Model):
journal = models.ForeignKey(Journal, related_name='volumes')
number = models.IntegerField()
class Issue(models.Model):
volume = models.ForeignKey(Volume, related_name='issues')
number = models.IntegerField()
class Article(models.Model):
issue = models.ForeignKey(Issue, related_name='articles')
title = models.CharField(max_length=255)
I need a JSON format like follow structure.
journal: [
{ name: 'Volume number goes here', type: 'folder', id: 'F1',
data: [
{ name: 'Issue number goes here', type: 'folder', id: 'F1F1',
data: [
{ name: 'Article name goes here>', type: 'item', id: 'F1F1I1' },
{ name: 'Article name goes here>', type: 'item', id: 'F1F1I2' },
{ name: 'Article name goes here>', type: 'item', id: 'F1F1I3' },
]},
{ name: 'Issue number goes here', type: 'folder', id: 'F1F2',
data: [
{ name: 'Article name goes here>', type: 'item', id: 'F1F2I1' },
{ name: 'Article name goes here>', type: 'item', id: 'F1F2I2' },
{ name: 'Article name goes here>', type: 'item', id: 'F1F2I3' },
]},
]
},
{ name: 'Volume number goes here', type: 'folder', id: 'F2',
data: [
{ name: 'Issue number goes here', type: 'folder', id: 'F1F1',
data: [
{ name: 'Article name goes here>', type: 'item', id: 'F2F1I1' },
{ name: 'Article name goes here>', type: 'item', id: 'F2F1I2' },
{ name: 'Article name goes here>', type: 'item', id: 'F2F1I3' },
]},
{ name: 'Issue number goes here', type: 'folder', id: 'F1F2',
data: [
{ name: 'Article name goes here>', type: 'item', id: 'F2F2I1' },
{ name: 'Article name goes here>', type: 'item', id: 'F2F2I2' },
{ name: 'Article name goes here>', type: 'item', id: 'F2F2I3' },
]},
]
}
],
I've tried several stuff but it will cause hundred of sql queries ( because of for loops )
Any ideas ?
You can create that JSON file using exactly 4 queries. You just have to use prefetch_related.
Here is some proof of concept (for queries counter to work, you must have DEBUG=True):
from django.db import connection
journals = Journal.objects.all().prefetch_related('volumes', 'volumes__issues', 'volumes__issues__articles')
for journal in journals:
print "%s" % journal.name
for volume in journal.volumes.all():
print " %d" % volume.number
for issue in volume.issues.all():
print " %d" % issue.number
for article in issue.articles.all():
print " %s" % article.title
print len(connection.queries)
That will print simple tree of your objects and number of queries at the end, which will equal 4 (if there wasn't any queries done before in that connection). From that there is not far to create your JSON output.
In creating that exact JSON, Django REST Framework can be helpful. Assuming that you have all your serializers done and nested, feeding JournalSerializer With above queryset, will create exactly 4 queries to database.
Use select_related and prefetch_related. These methods are used in the Django ORM to do SQL JOINs, so you won't be duplicating queries.
Related
When I use setSate() method on compiled component, the state is not being set.
The control is taking the state from the production code and not the state assigned from the test. Find the code below.
const wrapper = mount(<BookFlight />
wrapper.setState({ cabins: {
fields: [
{
label: 'Economy',
value: 'econ',
name: 'cabin',
type: 'radio'
},
{
label: 'Business',
value: 'business',
name: 'cabin',
type: 'radio'
},
{
label: 'First',
value: 'first',
name: 'cabin',
type: 'radio'
}
]
}})
expect(wrapper.state().cabins.fields.length).toBe(3)
I have a object, which has multiple objects
fields:[
{
safeName: 'status',
accessorName: 'Status',
type: {name: 'String', doc: 'String', code: '\'String\''},
field: {type: 'string', description: 'pet status in the store', enum: ['available', 'pending', 'sold']}
},
{
safeName: 'code',
accessorName: 'Code',
type: {name: 'NSInteger', doc: 'NSInteger', code: '\'NSInteger\'' },
field: {type: 'integer', format: 'int32'}
},
...
]
I need to check with enum value
Output should be
When enum is present in field
instance.status = Order.Status(rawValue: (sourceDictionary["status"] as? String) ?? "")
And when enum is not present in field object
instance.code = Decoders.decodeOptional(clazz: NSInteger.self, source: sourceDictionary["code"])
Did like this
{{#fields}}{{#field}}
{{#description}}
instance.{{safeName}} = Order.Status(rawValue: (sourceDictionary["{{safeName}}"] as? String) ?? "")
{{/description}}
{{^description}}
instance.{{safeName}} = Decoders.decodeOptional(clazz: {{#type}}{{type.name}}{{/type}}.self, source: sourceDictionary["code"])
{{/description}
{{/field}}{{/fields}}
I'm really struggling to understand how polymorphic relationships worm in Ember Data (Beta 11) and cannot find any update information on how to set them up and what is expected in the JSON payload. I'm trying to create a feed of items (think facebook feed) where you have different types of items in the feed. My modeling looks something like the following.
App.Feedable = DS.Model.extend({
activities: DS.hasMany('activity')
});
App.Activity = DS.Model.extend({
feedable: DS.belongsTo('feedable', { polymorphic: true, async: false })
});
App.MemberLikeShare = DS.Model.extend({
status: DS.attr('string')
});
App.PhotoShare = DS.Model.extend({
status: DS.attr('string'),
photo: DS.attr('string')
});
When I do a fetch at /activities I send back JSON that looks like the following:
{
activities: [
{
id: 1,
feedable: { id: 1, type: 'memberLikeShare' }
},
{
id: 4,
feedable: { id: 4, type: 'memberLikeShare' }
},
{
id: 5,
feedable: { id: 5, type: 'photoShare' }
}
],
member_like_shares: [
{
id: 1,
status: 'Foo'
},
{
id: 4,
status: 'Bar'
}
],
photo_shares: [
{id: 5, photo: 'example.jpg'}
]
}
When this runs I get an error like:
You can only add a 'feedable' record to this relationship Error: Assertion Failed: You can only add a 'feedable' record to this relationship
I'm assuming my relationships are wrong or I'm sending the wrong JSON?
polymorphic relationships should extend the base type.
App.Feedable = DS.Model.extend({
activities: DS.hasMany('activity')
});
App.MemberLikeShare = App.Feedable.extend({
status: DS.attr('string')
});
App.PhotoShare = App.Feedable.extend({
status: DS.attr('string'),
photo: DS.attr('string')
});
I'd also expect them to define the activities on them.
member_like_shares: [
{
id: 1,
status: 'Foo',
activites: [1,2,3,4]
},
{
id: 4,
status: 'Bar',
activites: [1,2,3,4]
}
],
photo_shares: [
{
id: 5,
photo: 'example.jpg',
activites: [1,2,3,4]
}
]
I'd like to be able to add class in the Itemtpl where the Item has it's field "Answered" set to "true"
It sound's easy to me, but I don't know where to start..
I know I have to check if Answered is true in the tpl, but I don't know how to write in the template.. o.O
//model
Ext.define('User', {
extend: 'Ext.data.Model',
config: {
idProperty: 'Name',
fields: [
{name: 'Name', type: 'string'},
{name: 'Address', type: 'string'},
{name: 'ID', type: 'int'},
{name: 'WebUrl', type: 'string'},
{name: 'InfoUrl', type: 'string'},
{name: 'Answered', type: 'boolean'},
]
}
});
//store
aStore = Ext.create('Ext.data.Store', {
model: 'User',
sorters: 'Name',
grouper: {
groupFn: function(record) {
return record.get('Name')[0];
}
}
});
//full store
store = Ext.create('Ext.data.Store', {
model: 'User',
sorters: 'Name',
grouper: {
groupFn: function(record) {
return record.get('Name')[0];
}
},
proxy: {
type: 'ajax',
url: '/Services/RestaurantList.ashx',
reader: {
type: 'json',
rootProperty: 'users'
}
},
listeners:{
load: function(){
var all = store.data.all;
aStore.setData(all.slice(0,30));
}
},
autoLoad: true
});
//the list
list = Ext.create('Ext.List', {
flex: 8,
itemTpl: ['<div class="contact">{Name}</div>'],
store: aStore,
listeners: {
itemtap: function(list, index, target, record) {
mainContainer.setActiveItem(1);
detailsPanel.setRecord(record);
},
plugins: [
{
xclass: 'Ext.plugin.PullRefreshFn',
refreshFn: function(){
store.clearData();
aStore.clearData();
store.clearFilter();
aStore.clearFilter();
store.load();
list.refresh();
}
}
],
grouped: true
});
Have you looked at the docs for XTemplate? http://docs.sencha.com/touch/2.2.1/#!/api/Ext.XTemplate. In particular, look at the "Conditional processing with basic comparison operators" section.
If you don't want to use the <tpl if=""> notation, you can also use the ternary operator:
itemTpl: new Ext.XTemplate(
'<div class="{[values.Answered ? \'answered\' : \'\']}">{Name}</div>'
),
...
See http://jsfiddle.net/cyclomarc/VXT53/6/
I have data in the form of:
publication: {
id: '1',
title: 'first title',
bodytext: 'first body',
author: {
id: '100',
name: 'Jan'
}
},
I want to show in the hbs part the author name. In the publications hbs (showing each publication), I use the following syntax, but that does not work:
{{publication.author.name}}
In the publications/edit hbs (edit of one publication after selection in publications), I use the following syntax, but that does not work:
{{author.name}}
How should I access the embedded data ?
First of, your working fiddle, sorry I ported it to jsbin since I like it more but this does not affect the functionality in any way: http://jsbin.com/ifukev/2/edit
Now to what I've changed, basically what I've done is to define that a App.Author has many publications and a App.Publication belongs to a App.Author and completed the respective FIXTURES:
App.Author = DS.Model.extend({
name: DS.attr('string'),
publications: DS.hasMany('App.Publication'),
didLoad: function () {
console.log('Author model loaded', this);
}
});
App.Publication = DS.Model.extend({
title: DS.attr('string'),
bodytext: DS.attr('string'),
author: DS.belongsTo('App.Author'),
didLoad: function () {
console.log('Publication model loaded', this);
}
});
//FIXTURES DATA
App.Publication.FIXTURES = [
{
id: '1',
title: 'first title',
bodytext: 'first body',
author: 100
},
{
id: '2',
title: 'second title',
bodytext: 'second post',
author: 300
}
];
App.Author.FIXTURES = [
{
id: '300',
name: 'Marc',
publications: [2]
},
{
id: '100',
name: 'Jan',
publications: [1]
}
];
Hope it helps.