With django-tables2 how do I display a model #property? - django-models

I have a #property in my model which is basically a string of several values in the model combined.
#property
def mfg_link(self):
return ''.join('http://mfg.com/model/' + str(self.model_numer))
I can add this mfg_link to the list_display on the admin model and it works fine, but its not showing up in the generated table when I pass the queryset to the table, the other fields show up fine.
This seems like something obvious, but unfortunately the couple of hours of searching didn't help.
Thanks a lot!

Do it like this in Table class:
class TableClass(tables.Table):
mfg_link = tables.Column('mfg_link', order_by='model_numer')
class Meta:
model = SomeModel
sequence = 'model_numer', 'mfg_link'

Related

Django Rest returning related items for each item

I was trying to find answer in similiar questions, but none was meeting my expectations.
I have 2 models:
class Artist(models.Model):
name = models.CharField(max_length=255)
music_type = models.CharField(max_lenght=50)
def __str__(self):
return self.name
class Event(models.Model):
event_name = models.CharField(max_length=255)
...
artists = models.ManyToManyField(Artist)
def __str__(self):
return self.event_name
I also have serializers.py file:
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
fields = '__all__'
class ArtistSerializer(serializers.ModelSerializer):
events = EventSerializer(source='event_set', many=True)
class Meta:
model = Artist
fields ='__all__'
The event in ArtistSerializer allows me to return all events where artist takes part.
Now for each artist I would like to get list of all artists if they ever were taking part in the same event.
For example I have 5 Artists (A1...A5) and 3 Events (E1...E3)
In Event 1: [A1,A3]
In Event 2: [A3,A4,A5,A2]
In Event 3: [A2, A3]
So for A3 I would like to get list [A1,A4,A5,A2]
For A1: [A3]
For A2: [A3,A4,A5]
Unfortunately I have huge problem to create this query as SQL-query and ORM mechanism looks more complicated in this situation. Can somebody help me with this problem or give hints how to solve this?
If it's needed I'm gonna share more code
You can query the through model to get the artists related to an event. This is the intermediate model which django will have created to make that M2M relationship.
Where you have a ManyToManyField it has an attribute of through which is the M2M model.
So from your event model you could do something like Event.artists.through.objects.all() and you'd see all the instances in your M2M model.
So to find out the artists which are linked to a given event you could query that same table;
Event.artists.through.objects.filter(event_id=1).select_related('artist')
This would then return all the objects in the M2M which belong to Event 1. You could then get the artists from there, or just grab the artist IDs Event.artists.through.objects.filter(event_id=1).values_list('artist_id, flat=True)
Given the scenario in your comment...
If you have an artist, then you can run a query to get the events they've been in, and then run another query with those event ids. In that second query you are then looking to get the artist ids that aren't the current artist you're already looking at.
# First get the events that the current artist has been in
event_ids = Event.artists.through.objects.filter(artist_id=1).values_list('event_id, flat=True)
# Then get the other artists who have been in the same events
other_artist_ids = Event.artists.through.objects.filter(event_id__in =event_ids).exclude(artist_id=1).values_list('artist_id, flat=True)
# or the full instances
other_artists = Event.artists.through.objects.filter(event_id__in =event_ids).exclude(artist_id=1).select_related('artist')

Django Inline model frontend

I need to have four file fields for my model so i am using Django inline model for that. I also need to create a model for with all thode fields so that the user can fill out the form and i am using Class based views- CreateView for that. However i do not know how to get the file fields in my model form.
Models.py
class Product(models.Model)
name= models.Charfield(maxlength=50)
city= models.Charfield(maxlength=50)
state=model.Charfield(maxlength=50)
year=models.Integerfield(blank=True, null=True)
class ProductAttachment(models.Model)
attachment = models.ForeignKey(Product, related_name='attachment')
appendix_a= models.Filefield(verbose_name='Appendix A')
appendix_b= models.Filedield(verbose_name='Appendix B')
Other = models.Filefield()
Admin.py
class ProductInline(admin.StackedInline)
model=ProductAttachment
class ProductAdmin(admin.modelAdmin)
inlines= [ProductInline,]
model=Product
admin.site.register(Product, ProductAdmin)
forms.py
class ProductForm(models.form):
class Meta:
model=Product
fields='__all__'
Views.py
class ProductCreateView(CreateView):
model=Product
form_class = ProductForm
However i do not know how to get all the filefield in the form. Any help is highly appreciated. Thank you
Looking at your code the model for your ProductForm and ProductCreateView is Product, which does not contain any FileFiled. You need to create form/view for ProductAttachment as well.

How to use hyperlinks to represent relationships instead of primary keys in Django REST framework

I want to get my object index as a "resource_uri" instead id
I take the usual way I make a model , views , serializers :
class User(BaseModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
models.CharField()
class UserSerailizers(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id','user','formatted_address')
classclass UserList(generics.ListCreateAPIView):
queryset = Image.objects.all()
serializer_class = UserSerializer
when i call < my_domain/user/ > I get this response
{
id:1,
name:'toto'
}
but I want to have an answer to this form:
{
'url': my_domain/user/1/
'name': 'toto'
}
Any thoughts?
If you want a hyperlink instead of a primary key in your model representations, you have to use either HyperlinkedModelSerializer or more generic Serializer along with HyperlinkedIdentityField and/or HyperlinkedRelatedField. The former is probably what you are looking for.
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys.
See Django REST framework documentation for more details.
As already commented, you need to use the HyperlinkedModelSerializer as you've shown.
The lookup_field attribute should be inside the Meta class.
And the latest and this is a guess: You just have a ListView for your User model. In order to show the detail for the user, you need also the retrieve method. I would recommend you using the ModelViewset so it automatically implements all methods.

Django: Single model for multiple tables

I have a main table
Slideshow
then a site specific table that captures a few extra details for that site.
Site1_Slideshow
In a web app (specific to a site) i want a single model i.e. Slideshow that combines the 2 tables above.
Currently i have the code below, but i dont think this is correct. I cant do things like
s = Slideshow.objects.get(slideshowId=1) as Slideshows only has the properties featurecategory and slideshow. So how can i have an model called Slideshow that is composed of these 2 tables but looks like it was a single db table.
class SlideshowAbstract(models.Model):
slideshowid = models.IntegerField(primary_key=True, db_column=u'SlideshowId') # Field name made lowercase.
headline = models.TextField(db_column=u'Headline') # Field name made lowercase.
class Meta:
db_table = u'Slideshow'
class Slideshow(models.Model):
slideshow = models.OneToOneField(SlideshowAbstract, primary_key=True,db_column=u'SlideshowId')
def __unicode__(self):
return self.slideshow.headline
class Meta:
db_table = u'Site1_Slideshow'
Think i found the solution.
On the Site1_Slideshow you need to add a column for django to use, that i presume is always the same as primary key value.
Its name is SlideshowAbstract_ptr_id
Once that is added you can change the Slideshow model to be
class Slideshow(SlideshowAbstract):
featureCategory = models.ForeignKey(Featurecategory,db_column=u'FeatureCategoryId')
def __unicode__(self):
return self.headline
class Meta:
db_table = u'Site1_Slideshow'
So doable but not the nicest if you are not doing "model first" and already have the schema. Would be good to be able to override the name of the _ptr_id column.
I did try adding the following to Slideshow too see if i could map this ptr col to the primary key
slideshowabstract_ptr_id = models.IntegerField(primary_key=True, db_column=u'SlideshowId')
but no cigar.
I havent tested inserts either but ...objects.all() works

How do I relate a Django model from a related table back to anoher record first model?

I have a course catalogue and am trying to include pre-requisits.
A course has 0 to n pre-requisits and a course can be the pre-quesit for 0 to n courses.
The course class is as follows
class Course(models.Model):
class Meta:
ordering = ['course_code', 'title']
course_id = models.AutoField(primary_key=True)
course_code = models.SlugField(max_length=20, null=False, blank=False)
....
....
class Pre_requisit(models.Model)
course = models.ForeignKey(Course, course_id')
pre_req = ???????
I have tried the pre_req field as a ForeginKey and MamyToManyField but cant find a solution.
Django will not allow 2 ForeignKeys from Pre_requisit class to the Course class.
With the ManyToMany field evn through another table I still get errors.
Can anyone let me know how to acheive this relationship.
I wish to ensure the pre-requisit course exists and be able to link to it so it can be displayed.
Many thanks.
class Course(models.Model):
....
pre_req = models.ManyToManyField("self")
read more at http://docs.djangoproject.com/en/dev/ref/models/fields/#manytomanyfield
If you wish to store extra info you can specify a "through" table also ( info at http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany) such as hard pre-requisite or recommended etc.

Resources