logo
down
shadow

How to force select_related() to select ForeignKeys that have null=True attribute?


How to force select_related() to select ForeignKeys that have null=True attribute?

By : Rodrigo Soares Tadew
Date : October 16 2020, 11:12 AM
will help you Yes, that is the way you would go about selecting related items with null=True.
Straight from the docs for select_related:
code :


Share : facebook icon twitter icon
Model.objects.all() returns integers for ForeignKeys and choice fields - how to force it to return names instead?

Model.objects.all() returns integers for ForeignKeys and choice fields - how to force it to return names instead?


By : Ahmed Mostafa
Date : March 29 2020, 07:55 AM
it should still fix some issue I assume you want to iterate through the fields, and pick out the ForeignKeys to handle specially:
code :
from django.db import models

# Get field_name, is_foreign_key pairs from model meta
fields_foreign = [(
   field.name, 
   isinstance(field, models.ForeignKey)
) for field in Contact._meta.fields]

# Assume every related model has a 'name' field,
# if you want to get 'name' fields of these models, 
# construct the list of field names to pass to values():
# something like ['url', 'email', 'person', 'bonus_field__name']
value_fields = [
    f[0] if not f[1] else "{}__name".format(f[0])
    for f in fields_foreign
]

# Now get the values
Contact.objects.values(*value_fields)
contacts = Contact.objects.all()
for contact in contacts:
    values = []
    for f in fields_foreign:
        value = getattr(contact, f[0])
        if f[1]: # Foreignkey, call str() on the model object
           value = str(value) # this calls __str__ in model
        values.append(value)
    print values
# Now we have tuples (field_name, is_field_foreign, field_has_choices)
fields_foreign_choices = [(
   field.name, 
   isinstance(field, models.ForeignKey),
   bool(field.choices)
) for field in Contact._meta.fields]

# We can use the magic get_field_display() method
contacts = Contact.objects.all()
for contact in contacts:
    values = []
    for f in fields_foreign_choices:
        value = getattr(contact, f[0])
        if f[1]: # Foreignkey, call str() on the model object
           value = str(value) # this calls __str__ in model
        elif f[2]: # The field has choices
           display_method = getattr(contact, "get_{}_display".format(f[0])
           value = display_method()
        values.append(value)
    print values
Force NULL to be a string in SELECT NULL FROM Table

Force NULL to be a string in SELECT NULL FROM Table


By : Rms
Date : March 29 2020, 07:55 AM
Hope this helps I am migrating some views and finally returning null for some columns for backward compatibility. However, when I change the column name to NULL AS [MyName], the column becomes an INT. , This will work.
code :
SELECT Convert(varchar(10), NULL) as MyName 
How to force an attribute to be present only if another one is true?

How to force an attribute to be present only if another one is true?


By : Jordi Morillo
Date : March 29 2020, 07:55 AM
I hope this helps you . I'm trying to validate a simple object using Joi. The schema i defined is the following: , You could try something like below:
code :
const singleReq = Joi.object({  
  subscribing: Joi.boolean(),  
  duration: Joi.number()
  .when('subscribing', { is: true, then: Joi.integer().positive().required() })
});
const schema = {
  a: Joi.alternatives().when('b', { is: 5, then: Joi.string(), otherwise: Joi.number() }),
  b: Joi.any()
};
select_related does not join columns marked with nulll=True

select_related does not join columns marked with nulll=True


By : user3804867
Date : March 29 2020, 07:55 AM
How to force Django Admin to use select_related?

How to force Django Admin to use select_related?


By : Наталья Буркот
Date : March 29 2020, 07:55 AM
I hope this helps . Although dr jimbob's answer makes sense, for my needs, I was able to simply override the get_queryset() method with a one-liner, even selecting a foreign key's foreign key. Maybe this could be helpful to someone.
Related Posts Related Posts :
  • Django REST Framework - SerializerMethodField is null on serializer.save()
  • Using Django Label Values
  • Reusing Django Changelist Outside of Admin Site
  • Django: Redirect logged in users from login page
  • Django: Extends or Include?
  • Checking a visitor's geographical location in a Django app
  • Are django sessisons safe to use for mission critical signup forms?
  • Django Admin: Path to file uploaded is wrong. Missing "static"?
  • define the queryset of ModelMultipleChoiceField in the widget
  • My Django manytomany fields are all marked unique, is there an option to remove this?
  • Django flatpages raising 404 when DEBUG is False (404 and 500 templates exist)
  • Django problem with extends template tag
  • Limit Django's inlineformset_factory to only create new objects
  • Django edit and delete from front end
  • Explanation of contribute_to_class
  • Dynamically Delete inline formsets in Django
  • Forward a copy of http requests to another (test) environment
  • How do I access the request from the request_finished signal callback?
  • django: Call to remote service kills python
  • which is the best django study book
  • Using a Non-Default Manager with GenericForeignKey()
  • Adding a link on the Django Admin frontpage
  • Django admin - stackedInline single instance
  • how to make certain that the queryset will be ordered by a valid field - django
  • Django: Filtering on a ("latitude, longitude") field
  • Search engine solution for Django that actually works?
  • Creating a db driven primary navigation in django?
  • Simulating Google Appengine's Task Queue with Gearman
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org