I have the following models:
class DecompositionGoal(Model):
id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
parent = ForeignKey(Goal, related_name='related_src')
child = ForeignKey(Goal, related_name='related_dst')
In Goal model there is a boolean field is_quantitative.
For the given parent I want to change is_quantitative field for each child.
Don't know how to apply inlineformset for this.
What are the ways of accomplishing this task?
Related
I have the following model:
class TopicModel(models.Model):
topic = models.ForeignKey('self', on_delete=models.CASCADE)
... some more not relevant fields...
I need to get a parent topic and its direct children in a queryset.
Currently I use it with this queryset:
TopicModel.objects.filter(
Q(pk=10) |
Q(topic__pk=10)
)
I was wondering whether I can do the same in a more simple query without using Q.
Is it possible, in Django, to create a module which is linked via a OneToOneField to another one, which only outputs a single field of its parent?
Something like:
class Venue(models.Model): # this is the parent
venue_name = models.CharField(max_length=50)
venue_city = models.CharField(max_length=50)
venue_country = models.CharField(max_length=50)
class VenueCity(models.Model): # should this be (Venue)?
venue_city = # this is the OneToOneField linked to the venue_city field of the parent
I need this because it'd be very handy for using it with a select2 field (
django_select2 - limit the returned text to a specific field in module) and I cannot use a #property, only a proper module.
** Addition: widget code **
class VenueForm(forms.ModelForm):
class Meta:
model = Venue
fields = ['venue_name', 'venue_city', 'venue_country']
widgets = {
'venue_city': s2forms.ModelSelect2Widget(model=Venue,
search_fields=['venue_city__icontains'])}
No, not as such. You could probably use Django-select2's label override function to show only the city name from the venue model, and maybe override the queryset too if you want uniquely cities only.
I have a "Parent" model, which contains multiple "Child" models and the relationship between Parent and Child holds the order of the children. Thus, I need a custom intermediary model.
models.py:
class Parent(models.Model):
name = models.CharField
children = models.ManyToManyField(Child, through=ParentChild)
...
class Child(models.Model):
name = models.CharField()
...
class ParentChild(model.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
child = models.ForeignKey(Child, on_delete=models.CASCADE)
order_of_child = IntegerField(null=True, blank=True, unique=True, default=None)
A Parent object is created based on a form and the Child objects to be part of the Parent object are selected by checkboxes.
Now my questions are: How can the order_of_child be included in the form and rendered alongside the checkboxes and how can the relationship be correctly saved in the view?
forms.py:
class ParentForm(ModelForm):
class Meta:
model = Parent
fields = ['name', 'children']
def __init__(self, *args, **kwargs):
super(ParentForm, self).__init__(*args, **kwargs)
self.fields['name'] = forms.CharField(label='Name', widget=forms.TextInput()
self.fields['children'] = ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple(queryset=Child.objects.all())
To save the relationship, you just first create and save the Parent, then loop through form.cleaned_data['children'] to create each ParentChild instance, assigning the index of the loop as the order.
Now for the order, that's more tricky, you'll need a widget that allows you to reorder the selection, so the default CheckboxSelectMultiple won't work because it doesn't do that. You need some javascript for that: Copy the selected options to a new div where the user can drag & drop to change the order, e.g. using a library such as jquery.ui.sortable or sortableJS/sortable. With javascript, you populate a hidden field with the selected values in the right order, which is what you submit in the end.
There's also a special django sortable multiselectfield package which I haven't tried (uses jqueryUI for sorting).
I have made an api that returns an object as json data. I Am using the django-rest-framework and its serializer. Using the resources (ModelResource) I excluded some fields, like a property called 'owner'. One of the fields is a foreignkey to itselve. I want to show this field in the api (so I use depth=2), but I want to exclude the same fields as I excluded in the object returning.
Is there a nice way to do this (I have tried several things without the wanted result).
This is my (simplified) code:
in models.py:
class MyObject(models.Model):
name = models.CharField(max_length=256, blank=True)
parent = models.ForeignKey('self', blank=True, null=True, default=None)
and_some_otherfields = models.otherFields(....)
owner = models.ForeignKey(User, null=True, blank=True, related_name='myobject_owner')
in resource.py:
class MyObjectResource(ModelResource):
model = MyObject
exclude = ('owner','and some other fields',)
and in the view used to return the object it returns this:
data = Serializer(depth=2).serialize(my_object)
return Response(status.HTTP_200_OK, data)
In the response it leaves out the exclude fields (as I wanted and expected).
but in the field parent, the parent myobject with all fields I want to hide.
I Am looking for a way to indicate that for this parent object, the serializer should use the same Resource, or add the secundary fields to the exclude list....
If I use depth =1 it only shows whether it has a parent ([]), or null if not, and i do need to know at least the parent's ID.
Ah, i just found it:
I need to add in the resource for all fields I want to show what resource....
fields = ('name', ("parent","MyObjectResource") , 'and all the other fields you want to see as well...')
I found it here: google groups forum question
You can skip the exlude, it ignores it, and just add the fields you want to show, you do not have to define them, unless you need to indicate what resource to use.
So following is the final code of the resource.py part:
class MyObjectResource(ModelResource):
model = MyObject
fields = ('name', ("parent","MyObjectResource"), 'and all the other fields you want to see as well...')
Here is how an other solution could be.
class ProToPicturesSerial(serializers.ModelSerializer):
pro_pictures = PictureSerializer(many=True)
pro_videos = VideoSerializer(many=True)
city_pro = CitySerializer(many=True)
class Meta:
model = Province
fields = ('id', 'name', 'intro', 'description', 'display_url', 'pro_pictures', 'pro_videos', 'city_pro')
Django has a unique_for_date property you can set when adding a SlugField to your model. This causes the slug to be unique only for the Date of the field you specify:
class Example(models.Model):
title = models.CharField()
slug = models.SlugField(unique_for_date='publish')
publish = models.DateTimeField()
What would be the best way to achieve the same kind of functionality for a non-DateTime field like a ForeignKey? Ideally, I want to do something like this:
class Example(models.Model):
title = models.CharField()
slug = models.SlugField(unique_for='category')
category = models.ForeignKey(Category)
This way I could create the following urls:
/example/category-one/slug
/example/category-two/slug
/example/category-two/slug <--Rejected as duplicate
My ideas so far:
Add a unique index for the slug and categoryid to the table. This requires code outside of Django. And would the built-in admin handle this correctly when the insert/update fails?
Override the save for the model and add my own validation, throwing an error if a duplicate exists. I know this will work but it doesn't seem very DRY.
Create a new slug field inheriting from the base and add the unique_for functionality there. This seems like the best way but I looked through the core's unique_for_date code and it didn't seem very intuitive to extend it.
Any ideas, suggestions or opinions on the best way to do this?
What about unique_together?
class Example(models.Model):
title = models.CharField()
slug = models.SlugField(db_index=False)
category = models.ForeignKey(Category)
class Meta:
unique_together = (('slug','category'),)
# or also working since Django 1.0:
# unique_together = ('slug','category',)
This creates an index, but it is not outside of Django ;) Or did I miss the point?