I have the (simple, I suppose) need of having a situation like so: there are many profiles, and there are many ensembles, and each profile has to be able to be part of one or more ensembles. This is my code:
class Ensemble(models.Model):
ensembleName = models.CharField(max_length=200)
members = models.ManyToManyField('Profile', related_name='members')
def __str__(self):
return self.ensembleName
class Profile(models.Model):
ensemble = models.ForeignKey(Ensemble, on_delete=models.CASCADE, blank=True, null=True)
[...]
It all works well, but to an extent. From the Django administration I can, from the 'ensemble' page, select its members. I can also select, from the 'profile' page, which ensembles that profile belongs. The issue is: they are not synchronised: if I add a profile to an ensemble via the 'profile' page this is not reflected in the 'ensemble' page and the other way round, i.e. in the 'profiles details' page I don't see the ensemble to which I previously assigned that profile from the 'ensemble' page.
My form
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('image', 'role', 'skills', 'gender', etc...)
class EnsemblesForm(forms.ModelForm):
class Meta:
model = Ensemble
fields = ('ensemble_name',)
def __init__(self, *args, **kwargs):
super(EnsemblesForm, self).__init__(*args, **kwargs)
self.fields['ensemble_name'].queryset = (obj for obj in Ensemble.objects.all()) #This doesn't output anything
Related
I have an example model which has a fk relation with user model and Blog model. Now I have a get api which only requires certain fields of user to be displayed.
My model:
class Example(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=True,
related_name="user_examples",
)
blog = models.ForeignKey(
Blog,
on_delete=models.CASCADE,
null=True,
related_name="blog_examples",
)
/................./
Now my view:
class ExampleView(viewsets.ModelViewSet):
queryset = Example.objects.all()
serializer_class = ExampleSerializer
def list(self, request, *args, **kwargs):
id = self.kwargs.get('pk')
queryset = Example.objects.filter(blog=id)
serializer = self.serializer_class(queryset,many=True)
return Response(serializer.data,status=200)
My serializer:
class ExampleSerializer(serializers.ModelSerializer):
class Meta:
model = Example
fields = ['user','blog','status']
depth = 1
Now when I call with this get api, I get all example objects that is required but all the unnecessary fields of user like password, group etc . What I want is only user's email and full name. Same goes with blog, I only want certain fields not all of them. Now how to achieve this in a best way??
You will have to specify the required fields in nested serializers. e.g.
class BlogSerializer(serializers.ModelSerializer):
class Meta:
model = Blog
fields = ['title', 'author']
class ExampleSerializer(serializers.ModelSerializer):
blog = BlogSerializer()
class Meta:
model = Example
fields = ['user','blog','status']
are you setting depth in serializer's init method or anywhere else? beacause ideally it should only display id's and not anything else. if yes then set depth to zero and use serializer's method field to return data that you need on frontend. I can provide you with example code samples
I have Django database with 2 models: DeviceModel and Device. Let's say, for example, DeviceModel object is "LCD panel" and Device object is "LCD panel №547". So these two tables have ManyToOne relationship.
class DeviceModel(models.Model):
name = models.CharField(max_length=255)
class Device(models.Model):
device_model = models.ForeignKey(DeviceModel)
serial_number = models.CharField(max_length=255)
Now I need to add some relations between DeviceModel objects. For example "LCD Panel" can be in "Tablet" object or in "Monitor" object. Also another object can be individual, so it doesn't link with other objects.
I decided to do this with ManyToMany relationship, opposed to using serialization with JSON or something like that (btw, which approach is better in what situation??).
I filled all relationships between device models and know I need to add relationship functional to Device table.
For that purpose I added "master_dev" foreignkey field pointing to 'self'. It works exactly as I need, but I want to restrict output in django admin panel. It should display only devices, that are connected through device_links. Current code:
class DeviceModel(models.Model):
name = models.CharField(max_length=255)
device_links = models.ManyToManyField('self')
class Device(models.Model):
device_model = models.ForeignKey(DeviceModel)
serial_number = models.CharField(max_length=255)
master_dev = models.ForeignKey('self', blank=True, null=True)
So, how can I limit output of master_dev field in admin panel?
There is a function "limit_choices_to", but I can't get it to work...
in forms.py:
def master_dev_chioses():
chioses = DeviceModel.objects.filter(do your connection filter here - so not all Devicemodels comes to choicefield)
class DeviceForm(forms.ModelForm):
class Meta:
model = Device
def __init__(self, *args, **kwargs):
super(Device, self).__init__(*args, **kwargs)
self.fields['master_dev'].choices = master_dev_chioses()
While there is no direct answer to my question about "limit_choices_to" function, I post solution that achieves desired output:
from django import forms
from django.contrib import admin
from .models import DeviceModel, Device
class DeviceForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(DeviceForm, self).__init__(*args, **kwargs)
try:
linked_device_models = self.instance.device_model.device_links.all()
linked_devices = Device.objects.filter(device_model__in=linked_device_models)
required_ids = set(linked_devices.values_list("id", flat=True))
self.fields['master_dev'].queryset = Device.objects.filter(id__in=required_ids).order_by("device_model__name", "serial_number")
except:
# can't restrict masters output if we don't know device yet
# admin should edit master_dev field only after creation
self.fields['master_dev'].queryset = Device.objects.none()
class Meta:
model = Device
fields = ["device_model", "serial_number", "master_dev"]
class DeviceAdmin(admin.ModelAdmin):
form = DeviceForm
list_display = ('id', 'device_model', 'serial_number')
list_display_links = ('id', 'device_model')
search_fields = ('device_model__name', 'serial_number')
list_per_page = 50
list_filter = ('device_model',)
I am trying to sort out a specific problem that involve "many2many" relationship using through specification.
I've already tried to use inline_factory but I was not able to sort out the problem.
I have these tables
class Person(models.Model):
id = models.AutoField(primary_key=True)
fullname = models.CharField(max_length=200)
nickname = models.CharField(max_length=45, blank=True)
class Meta:
db_table = 'people'
class Role(models.Model):
role = models.CharField(max_length=200)
class Meta:
verbose_name_plural = 'roles'
db_table = 'roles'
class Study(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=255)
description = models.CharField(max_length=1000)
members = models.ManyToManyField(Person, through='Studies2People')
class Meta:
db_table = 'studies'
class Studies2People(models.Model):
person = models.ForeignKey(Person)
role = models.ForeignKey(Role)
study = models.ForeignKey(Study)
class Meta:
verbose_name_plural = 'studies2people'
db_table = 'studies2people'
unique_together = (('person', 'role', 'study'),)
#forms.py
from .models import Study, Person, Role, Studies2People
class RegisterStudyForm(ModelForm):
class Meta:
model = Study
fields = '__all__'
#View.py
class StudyCreateView(CreateView):
template_name = 'managements/register_study.html'
model = Study
form_class = RegisterStudyForm
success_url = 'success/'
def get(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
return self.render_to_response(self.get_context_data(form=form))
The code above creates a form like:
Study.Title
Study.description
List of People
I want to create a form to fill in all fields that involve Studies2People Something like this:
Study.Title
Study.description
Combo(people.list)
Combo(Role.list)
Maybe I should start from Studies2People but I don't know how to show the "inline" forms involved.
Thanks in advance
C.
waiting someone that is able to explain with some examples the relationship m2m with through (model & view), I sorted out my problem in a different way.
I've created three forms.
1 Model Form (study)
2 Form (forms with ModelChoiceField(queryset=TableX.objects.all())
Created a classView to manage the get and post action.(validation form too)
In the post procedure I used "transaction" to avoid "fake" data.
I hope that someone will post an example with complex m2m relationships.
Regards
Cinzia
I have a fairly basic model that allows users to create posts of different 'types'. There's currently a Text type and a Photo type that inherits from a base 'Post' type.
I'm currently pulling TextPosts and PhotoPosts and chaining the two QuerySets, but this seems like a bad idea.
Is there a way to simply query for both types of posts at once? The reason I'm not using .filter() on Post itself is because I (presumably) don't have any way of getting the TextPost or PhotoPost object from it (or do I?)
PS: Does it make more sense to call it BasePost or Post if I'll never be using Post by itself?
class Post(AutoDateTimeModel):
POST_TYPES = (
# Linkable Social Networks
('TEXT', 'Text'),
('PHOTO', 'Photo'),
('LINK', 'Link'),
)
post_type = models.ForeignKey(ContentType)
user = models.ForeignKey(User, blank=True, null=True)
interests = models.ManyToManyField(Interest, related_name='interests')
class Meta:
app_label = 'posts'
ordering = ('-created_at',)
def save(self, *args, **kwargs):
if not self.pk:
self.post_type = ContentType.objects.get_for_model(type(self))
# import pdb; pdb.set_trace()
super(Post, self).save(*args, **kwargs)
class TextPost(Post):
""" Text post model """
body = models.TextField()
class Meta:
app_label = 'posts'
class PhotoPost(Post):
""" Photo post model. This can contain multiple photos. """
description = models.TextField()
class Meta:
app_label = 'posts'
class Photo(models.Model):
""" Individual image model, used in photo posts. """
caption = models.TextField()
# source_url = models.URLField(blank=True, null=True)
image = ImageField(upload_to=upload_to)
post = models.ForeignKey(PhotoPost, blank=True, null=True, related_name='photos')
user = models.ForeignKey(User, blank=True, null=True, related_name='photos')
class Meta:
app_label = 'posts'
def __unicode__(self):
return 'Photo Object by: ' + str(self.user.get_full_name())
You can use this nice app django-model-utils, using InheritanceManager in your Post class.
A nice example from the docs:
from model_utils.managers import InheritanceManager
class Place(models.Model):
# ...
objects = InheritanceManager()
class Restaurant(Place):
# ...
class Bar(Place):
# ...
nearby_places = Place.objects.filter(location='here').select_subclasses()
for place in nearby_places:
# "place" will automatically be an instance of Place, Restaurant, or Bar
Applying for your situation:
class Post(AutoDateTimeModel):
...
objects = InheritanceManager()
class TextPost(Post):
...
class PhotoPost(Post):
...
And this answers your question: Is there a way to simply query for both types of posts at once?
You can query for posts now, resulting instances of TextPost and Photoposts
I have one listing model :
class Listing(models.Model):
owner = models.ForeignKey(User, verbose_name=_('offerer'))
title = models.CharField(_('Title'), max_length=255)
slug = models.CharField(editable=False, max_length=255)
price = models.PositiveIntegerField(_("Price"), null=True, blank=True)
description = models.TextField(_('Description'))
time = models.DateTimeField(_('Created time'),
default = datetime.now,
editable = False
)
Then I have one ListingImage, which holds the pictures of the listing:
from photologue.models import ImageModel
class ListingImage(ImageModel):
pictures = models.ForeignKey(Listing, related_name="images")
forms.py
class ListingForm(forms.ModelForm):
class Meta:
model = Listing
exclude = ('owner',)
def __init__(self, *args, **kwargs):
super(ListingForm, self).__init__(*args, **kwargs)
Why in the upload page , there is no field to upload a picture??
ListingImage has a ForeignKey to Listing, so a ModelForm for Listing has nothing to do with ListingImage.
You shouldn't be expecting a ModelForm for the Listing model to show you anything but the Listing model. ListingImage is a reverse relationship to the Listing model.
If this was a ModelAdmin, you'd get the admin site to show you these reverse relationships by defining inlines:
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin
Since it doesn't look like you're talking about the admin panel, you're looking at InlineModelFormsets: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-an-inline-formset-in-a-view
Also, you could show us your views so that we can see the whole picture.